c语言多线程问题
发布网友
发布时间:2022-04-20 03:22
我来回答
共1个回答
热心网友
时间:2022-05-12 22:37
#include <stdio.h>
#include <process.h>
#include <windows.h>
long g_nNum; //全局资源
unsigned int __stdcall Fun(void *pPM); //线程函数
const int THREAD_NUM = 10; //子线程个数
int main()
{
g_nNum = 0;
HANDLE handle[THREAD_NUM];
int i = 0;
while (i < THREAD_NUM)
{
handle[i] = (HANDLE)_beginthreadex(NULL, 0, Fun, &i, 0, NULL);
i++;//等子线程接收到参数时主线程可能改变了这个i的值
}
//保证子线程已全部运行结束
WaitForMultipleObjects(THREAD_NUM, handle, TRUE, INFINITE);
return 0;
}
unsigned int __stdcall Fun(void *pPM)
{
//由于创建线程是要一定的开销的,所以新线程并不能第一时间执行到这来
int nThreadNum = *(int *)pPM; //子线程获取参数
Sleep(75);//some work should to do
g_nNum++; //处理全局资源
Sleep(1);//some work should to do
printf("线程编号为%d 全局资源值为%d\n", nThreadNum, g_nNum);
getch();
return 0;
}