温馨提示×

C++中Linux多线程怎样实现

小樊
33
2025-02-20 05:45:51
栏目: 编程语言
C++开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在C++中,Linux平台下可以使用POSIX线程库(pthread)来实现多线程。以下是一个简单的示例,展示了如何创建和运行多个线程:

#include <iostream>
#include <pthread.h>

// 线程函数
void* thread_function(void* arg) {
    int thread_id = *(static_cast<int*>(arg));
    std::cout << "线程 " << thread_id << " 正在运行" << std::endl;
    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_threads; ++i) {
        thread_ids[i] = i;
        if (pthread_create(&threads[i], nullptr, thread_function, &thread_ids[i]) != 0) {
            std::cerr << "创建线程失败" << std::endl;
            return 1;
        }
    }

    // 等待线程结束
    for (int i = 0; i < num_threads; ++i) {
        pthread_join(threads[i], nullptr);
    }

    std::cout << "所有线程已结束" << std::endl;
    return 0;
}

要编译这个程序,请使用以下命令:

g++ -o multi_thread_example multi_thread_example.cpp -pthread

然后运行生成的可执行文件:

./multi_thread_example

这个示例中,我们创建了5个线程,每个线程都会打印其线程ID。注意,在实际应用中,你可能需要处理线程同步、互斥等问题,以避免竞争条件和数据不一致。在这种情况下,可以使用互斥锁(pthread_mutex_t)和其他同步原语。

亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读:linux c++多线程怎样实现

0