</pre><pre name="code" class="cpp">
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
int n = 1;
int N = 100;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//pthread_mutex_init(&mutex);
void *func1(void* arg)
{
while(n < N+1)
{
pthread_mutex_lock(&mutex);
printf("func1 %d\n",n);
n++;
sleep(1);
//printf("hello1\n");
pthread_mutex_unlock(&mutex);
//printf("hello2\n");
sleep(1);
//printf("hello3\n");
}
}
void *func2(void* arg)
{
while(n < N+1)
{
pthread_mutex_lock(&mutex);
printf("func2 %d\n",n);
n++;
sleep(1);
//printf("world1\n");
pthread_mutex_unlock(&mutex);
//printf("world2\n");
sleep(1);
//printf("world3\n");
}
}
int main(int argc, char** argv)
{
pthread_t pid1,pid2;
if((pthread_create(&pid1,NULL,func1,NULL)) != 0)
printf("pthread create error\n");
sleep(1);
if((pthread_create(&pid2,NULL,func2,NULL)) != 0)
printf("pthread create error\n");
pthread_join(pid1,NULL);
pthread_join(pid2,NULL);
return 0;
}
windows
<pre name="code" class="cpp">#include <stdio.h>
#include <windows.h>
int n=0;
HANDLE hEvent;
DWORD WINAPI ThreadFunc(LPVOID lpParam)
{
WaitForSingleObject(hEvent,INFINITE);//实现互斥访问
while(n<100)
{
Sleep(100);
n++;
printf("the count=%d\n",n);
}
SetEvent(hEvent);
}
DWORD WINAPI Add(LPVOID lpParam)
{
WaitForSingleObject(hEvent,INFINITE);
while(n<100)
{
Sleep(100);
n++;
printf("the count=%d\n",n);
}
SetEvent(hEvent);
}
int main()
{
HANDLE hThread,hThread1;
DWORD dwThreadId,dwThreadId1;
hEvent=CreateEvent(NULL,FALSE,TRUE,NULL);//创建事件对象
hThread=CreateThread(NULL,NULL,ThreadFunc,NULL,0,&dwThreadId);//创建线程
hThread1=CreateThread(NULL,NULL,Add,NULL,0,&dwThreadId1);
printf("the dwThreadId =%d\n",dwThreadId);
printf("the dwThreadId =%d\n",dwThreadId1);
WaitForSingleObject(hThread,INFINITE);
WaitForSingleObject(hThread1,INFINITE);
CloseHandle(hThread);//关闭线程句柄
CloseHandle(hThread1);
return 0;
}