win32多线程实现交替打印A B C
本帖最后由 aswcy815174418 于 2021-5-23 01:01 编辑**大家可以自己试试实现,得分别用一个线程打印A,B,C
代码:**
```
#include "stdio.h"
#include <windows.h>
DWORD WINAPI ThreadA(LPVOID parameter) {
HANDLE* eventHandle = (HANDLE*)parameter;
//等待A通知,通知后执行下面代码并修改A为未通知(原因如下)
//CreateEvent(NULL ,FALSE ,TRUE ,NULL); 第二个参数为FALSE
WaitForSingleObject(eventHandle ,-1);
printf("A");
//设置事件B为已通知,接下来的代码逻辑差不多,就是A->B->C->A.......
SetEvent(eventHandle);
return 0;
}
DWORD WINAPI ThreadB(LPVOID parameter) {
HANDLE* eventHandle = (HANDLE*)parameter;
WaitForSingleObject(eventHandle ,-1);
printf("B");
SetEvent(eventHandle);
return 0;
}
DWORD WINAPI ThreadC(LPVOID parameter) {
HANDLE* eventHandle = (HANDLE*)parameter;
WaitForSingleObject(eventHandle ,-1);
printf("C\n");
SetEvent(eventHandle);
return 0;
}
DWORD WINAPI ThreadCreate(LPVOID parameter) {
//事件句柄数组
HANDLE eventHandle = { 0 };
eventHandle = CreateEvent(NULL ,FALSE ,TRUE ,NULL);
eventHandle = CreateEvent(NULL ,FALSE ,FALSE ,NULL);
eventHandle = CreateEvent(NULL ,FALSE ,FALSE ,NULL);
//线程句柄数组
HANDLE hThread = { 0 };
for ( size_t i = 0; i < 10; i++ ) {
hThread = CreateThread(0 ,0 ,ThreadA ,(LPVOID)eventHandle ,0 ,0);
hThread = CreateThread(0 ,0 ,ThreadB ,(LPVOID)eventHandle ,0 ,0);
hThread = CreateThread(0 ,0 ,ThreadC ,(LPVOID)eventHandle ,0 ,0);
//等待所有线程跑完
WaitForMultipleObjects(3,hThread ,TRUE,-1);
//关闭所有线程句柄
CloseHandle(hThread);
CloseHandle(hThread);
CloseHandle(hThread);
}
//关闭所有线程句柄
CloseHandle(eventHandle);
CloseHandle(eventHandle);
CloseHandle(eventHandle);
return 0;
}
int main(int argc ,char* argv[]) {
//创建线程避免卡死主线程
CreateThread(0,0,ThreadCreate,0,0,0);
//让线程跑一会,直到输入任意字符
getchar();
return 0;
}
``` 学习了试试看 前排支持,感谢分享 千山万水过来支持一下 leetcode最近出的多线程的题 可以看看题解
https://leetcode-cn.com/problems/print-in-order/ 感谢分享 不错,学习一下 本帖最后由 prochsh 于 2021-5-24 11:39 编辑
推荐你看看C++11,多线程跟系统无关,提供一个例子,原子操作,不需要添加锁
#include <atomic>
#include <thread>
atomic<int> a;
atomic<int> b;
int Thread1(int) {
int t = 1;
a.store(t, memory_order_relaxed);
b.store(2, memory_order_release);// 本原子操作前所有的写原子操作必须完成
return 0;
}
int Thread2(int) {
while (b.load(memory_order_acq_rel) != 2); // 本原子操作必须完成才能执行之后所有的读原子操作
cout << a.load(memory_order_relaxed) << endl;
return 0;
}
int main()
{
thread t1(Thread1, 0);
thread t2(Thread2, 0);
t1.join();
t2.join();
return 0;
} prochsh 发表于 2021-5-24 11:37
推荐你看看C++11,多线程跟系统无关,提供一个例子,原子操作,不需要添加锁
#incl ...
{:1_896:}就最近学到win32api了就来试试
页:
[1]
2