vc6线程问题!

来源:百度知道 编辑:UC知道 时间:2024/06/08 09:18:36
我写了如下程序:
#include "stdafx.h"
#include <windows.h>
DWORD WINAPI helloFunc(LPVOID arg){
int i,*N =(int*)arg;
for(i = 0; i <18;i++)
{
printf("Thread %d run in %d\n",*N,i+1);
}
ExitThread(0);
return 0;
}
int main(int argc, char *argv[])
{
HANDLE thread[3];
int x = 0,y = 1,z = 2;
thread[0] = CreateThread(NULL,0,helloFunc,&x,0,NULL);
thread[1] = CreateThread(NULL,0,helloFunc,&y,0,NULL);
thread[2] = CreateThread(NULL,0,helloFunc,&z,0,NULL);
WaitForMultipleObjects(1,thread,TRUE,INFINITE);
printf("第一个模拟进程运行完毕\n");
WaitForMultipleObjects(3,thread,TRUE,INFINITE);
printf("三个模拟进程全部运行完毕\n");
return 0;
}

打印如下内容:
Thread 0 run in 1
Thread 0 run in 2
Thread 0 run in 3
Thread 0 run in 4
Thread 0 run in 5
Thread 0 run in 6

同步问题吧~!用个互斥对象吧~

#include <stdio.h>
#include <windows.h>

HANDLE hMutex;

DWORD WINAPI helloFunc(LPVOID arg)
{
WaitForSingleObject(hMutex,INFINITE);
int i,*N =(int*)arg;

for(i = 0; i <18;i++)
{
printf("Thread %d run in %d\n",*N,i+1);
}
ReleaseMutex(hMutex);
ExitThread(0);
return TRUE;
}
int main(int argc, char *argv[])
{
HANDLE thread[3];
int x = 0,y = 1,z = 2;
hMutex = CreateMutex(NULL,FALSE,NULL);
thread[0] = CreateThread(NULL,0,helloFunc,&x,0,NULL);
thread[1] = CreateThread(NULL,0,helloFunc,&y,0,NULL);
thread[2] = CreateThread(NULL,0,helloFunc,&z,0,NULL);
WaitForMultipleObjects(3,thread,TRUE,INFINITE);
printf("三个模拟进程全部运行完毕\n");
return 0;
}

同步问题.看你这个3个线程都是执行相同的代码,就用临界区对象吧
#include "stdafx.h"
#include "stdio.h"