要使用pthread库,需要引入头文件`#include `。 下面是一个简单的示例,展示了如何使用pthread库创建和运行一个线
要使用pthread库,需要引入头文件`#include
下面是一个简单的示例,展示了如何使用pthread库创建和运行一个线程。
#include
#include
// 线程函数,用于并行执行的任务
void* threadFunction(void* arg) {
std::cout << "Hello from thread!" << std::endl;
return nullptr;
}
int main() {
pthread_t threadId; // 存储线程ID的变量
// 创建线程,传入线程函数和参数
int result = pthread_create(&threadId, nullptr, threadFunction, nullptr);
if (result != 0) {
std::cerr << "Failed to create thread." << std::endl;
return 1;
}
// 等待线程结束
result = pthread_join(threadId, nullptr);
if (result != 0) {
std::cerr << "Failed to join thread." << std::endl;
return 1;
}
std::cout << "Thread completed." << std::endl;
return 0;
}
在这个示例中,`pthread_create()`函数用于创建一个新线程,并将线程ID存储在`threadId`变量中。该函数的参数包括线程ID变量、线程属性(可设置为`nullptr`,使用默认属性)、线程函数和函数参数。
创建线程后,可以使用`pthread_join()`函数等待线程完成。`pthread_join()`函数将阻塞主线程,直到指定的线程执行完毕。
--结束END--
本文标题: c++ pthread库怎么调用
本文链接: https://www.lsjlt.com/news/450570.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-03-01
2024-03-01
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
2024-02-29
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0