阅读量:46
在Linux上使用C++实现多线程,主要依赖于POSIX线程库(pthread)。以下是一个简单的示例,展示了如何在C++中使用pthread创建和管理线程。
-
首先,确保你的系统已经安装了pthread库。在大多数Linux发行版中,它已经是预装的。如果没有,你可以使用包管理器(如apt或yum)来安装它。
-
创建一个名为
multithread_example.cpp的文件,并添加以下代码:
#include
#include
// 线程函数
void* thread_function(void* arg) {
int thread_id = *(static_cast<int*>(arg));
std::cout << "Hello from thread " << thread class="hljs-keyword">return nullptr;
}
int main() {
const int num_threads = 5;
pthread_t threads[num_threads];
int thread_ids[num_threads];
// 创建线程
for (int i = 0; i < num xss=removed class="hljs-keyword">if (pthread_create(&threads[i], nullptr, thread_function, &thread_ids[i]) != 0) {
std::cerr << "Error creating thread "<< i class="hljs-keyword">return 1;
}
}
// 等待线程结束
for (int i = 0; i < num class="hljs-built_in">pthread_join(threads[i], nullptr);
}
std::cout << "All threads finished." << std class="hljs-keyword">return 0;
}
- 使用g++编译器编译代码:
g++ -o multithread_example multithread_example.cpp -lpthread
- 运行生成的可执行文件:
./multithread_example
这个示例将创建5个线程,每个线程都会输出一条消息。注意,由于线程的执行顺序是不确定的,输出的顺序可能会有所不同。
在实际应用中,你可能需要使用互斥锁、条件变量等同步原语来确保线程之间的正确通信和同步。这些功能都可以在pthread库中找到。