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

C++并发编程入门 目录

STL 写法

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

void thread_fun1(void)
{
    cout << "one STL thread 1!" << endl;
}

void thread_fun2(void)
{
    cout << "one STL thread 2!" << endl;
}

int main(void)
{
    std::thread thread1(thread_fun1);
    std::thread thread2(thread_fun2);

    thread1.join();
    thread2.join();

    return 0;
}

Windows 写法

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

DWORD WINAPI ThreadFun1(LPVOID lpParamter)
{
    cout << "one Windows thread 1!" << endl;
    return 0;
}
DWORD WINAPI ThreadFun2(LPVOID lpParamter)
{
    cout << "one Windows thread 2!" << endl;
    return 0;
}

int main()
{
    HANDLE hThread1 = CreateThread(NULL, 0, ThreadFun1, NULL, 0, NULL);
    HANDLE hThread2 = CreateThread(NULL, 0, ThreadFun2, NULL, 0, NULL);

    HANDLE handleArr[] = { hThread1 , hThread2 };
    //等待两个线程结束
    WaitForMultipleObjects(2, handleArr, TRUE, INFINITE);
    
    CloseHandle(hThread1);
    CloseHandle(hThread2);

    return 0;
}

三次执行结果

每个线程都打印一句话

第一个线程和第二个线程交叉占用控制台

居然是先执行的第二个线程

Linux 写法

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

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

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

int main(void)
{
    pthread_t thread_id1;
    pthread_t thread_id2;

    pthread_create(&thread_id1, NULL, thread_fun1, NULL);
    pthread_create(&thread_id2, NULL, thread_fun2, NULL);

    //让线程运行直到结束
    pthread_join(thread_id1, NULL);
    pthread_join(thread_id2, 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、付费专栏及课程。

余额充值