說真的寫了這篇博文時,才知道c語言本身不支持多線程,而是一些windowsapi讓c語言擁有多線程的能力,那下面內容就以打開對話框為例,展現(xiàn)如何實現(xiàn)多線程的同步與異步。
問題起源
想要實現(xiàn)c語言打開多個對話框的多線程同步與異步
c語言多線程同步方案
#include<Windows.h>
#include<stdio.h>
#include<stdlib.h>
DWORD WINAPI mymsg(LPVOID lp) {
MessageBoxA(0, "hello", "china", 0);
}
int main() {
HANDLE hthread;
DWORD threadid;
for (int i = 0; i < 5; i++) {
hthread = CreateThread(
NULL,
NULL,
mymsg,
NULL,
0,
&threadid
);
WaitForSingleObject(hthread
, INFINITE);
}
getchar();
return 0;
}
代碼效果
c語言多線程異步方案
#include<Windows.h>
#include<stdio.h>
#include<stdlib.h>
DWORD WINAPI mymsg(LPVOID lp) {
MessageBoxA(0, "hello", "china", 0);
}
int main() {
HANDLE hthread;
DWORD threadid;
for (int i = 0; i < 5; i++) {
hthread = CreateThread(
NULL,
NULL,
mymsg,
NULL,
0,
&threadid
);
}
getchar();
return 0;
}
文章來源:http://www.zghlxwxcb.cn/news/detail-788076.html
總結
對代碼的查閱會發(fā)現(xiàn),關鍵在于定義多線程的函數(shù)與句柄,最后一個循環(huán)分別創(chuàng)建一個線程即可。文章來源地址http://www.zghlxwxcb.cn/news/detail-788076.html
到了這里,關于【已解決】C語言實現(xiàn)多線程的同步與異步的文章就介紹完了。如果您還想了解更多內容,請在右上角搜索TOY模板網以前的文章或繼續(xù)瀏覽下面的相關文章,希望大家以后多多支持TOY模板網!