创建10个线程并发执行(STL/Windows/Linux)

本文介绍了在C++中使用STL、WindowsAPI和POSIXAPI(如Linux的pthread)实现并发编程的基本示例,展示了如何创建和管理线程以进行并行处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

C++并发编程入门 目录

STL 写法

#include <thread>
#include <iostream>
using namespace std;

void thread_fun(int arg)
{
    cout << "one STL thread " << arg << " !" << endl;
}

int main(void)
{
    int thread_count = 10;
    int id_array[10] = { 1,2,3,4,5,6,7,8,9,10 };

    std::thread thread_arr[10] = { };

    for (int i = 0; i < thread_count; i++)
    {
        thread_arr[i] = std::thread(thread_fun, id_array[i]);
    }

    for (int i = 0; i < thread_count; i++)
    {
        thread_arr[i].join();
    }

    return 0;
}

Windows 写法

#include <iostream>
#include <windows.h>
using namespace std;

DWORD WINAPI ThreadFun(LPVOID lpParamter)
{
    //转成整数地址,再对地址解引用取出整数
    cout << "one Windows thread "<< *(int*)lpParamter<<" !" << endl;
    return 0;
}

int main()
{
    int thread_count = 10;
    HANDLE handleArr[10] = {NULL};
    //给线程函数传递的数据,用来标记线程
    int data[10] = { 1,2,3,4,5,6,7,8,9,10 };
    for (int i = 0; i < 10; i++)
    {
        handleArr[i] = CreateThread(NULL, 0, ThreadFun, &data[i], 0, NULL);
    }

    //等待10个线程结束
    WaitForMultipleObjects(thread_count, handleArr, TRUE, INFINITE);

    for (int i = 0; i < thread_count; i++)
    {
        CloseHandle(handleArr[i]);
    }

    return 0;
}

一次执行结果


 

另一次执行结果

Linux 写法

#include <pthread.h>
#include <iostream>
using namespace std;

void* thread_fun(void *arg)
{
    cout << "one Linux thread "<< *(int*)arg<<" !" << endl;
    return 0;
}

int main(void)
{
    int thread_count = 10;
    int id_array[10] = { 1,2,3,4,5,6,7,8,9,10 };
    pthread_t thread_arr[10] = { 0 };

    for (int i = 0; i < thread_count; ++i)
    {
        pthread_create(&thread_arr[i], NULL, thread_fun, &id_array[i]);
    }

    //让线程运行直到结束
    for (int i = 0; i < thread_count; i++)
    {
        pthread_join(thread_arr[i], NULL);
    }

    return 0;
}

一次执行结果

另一次的执行结果

再一次执行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

C++程序员Carea

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值