创建两个线程MyThreadProc1和MyThreadProc2;
#include <windows.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
DWORD WINAPI MyThreadProc1(LPVOID lpParameter);
DWORD WINAPI MyThreadProc2(LPVOID lpParameter);
int index = 0;
int i = 0 , y = 0;
int main()
{
HANDLE handle1,handle2;
handle1 = CreateThread(NULL,0,MyThreadProc1,NULL,0,NULL);
handle2 = CreateThread(NULL,0,MyThreadProc2,NULL,0,NULL);
if(NULL == handle1)
{
cout<<"Create Thread failed !"<<endl;
return -1;
}
if(NULL == handle2)
{
cout<<"Create Thread failed !"<<endl;
return -1;
}
CloseHandle(handle1);
CloseHandle(handle2);
cout<<"The Main Thread is Running !"<<endl;
system("PAUSE");
return 0;
}
DWORD WINAPI MyThreadProc1(LPVOID lpParameter)
{
cout<<"The MyThreadProc1 is Running !"<<endl;
return 0;
}
DWORD WINAPI MyThreadProc2(LPVOID lpParameter)
{
cout<<"The MyThreadProc2 is Running ! "<<endl;
return 0;
}
对线程进行参数传递。注意传递多个参数需要创建结构体,然后使用(void *)空类型对创建的结构体进行传递。
现在我们能建立了一个线程了,我们可以从函数的原型看到,在创建线程的时候,是可以在对我们的函数进行传递参数,在pthread_create的第四个行参。我们看一下例题2~3.
例题2
功能:向新的线程传递整形值
程序名称:pthread_int.c
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *create(void *arg)
...{
int *num;
num=(int *)arg;
printf("create parameter is %d ",*num);
return (void *)0;
}
int main(int argc ,char *argv[])
...{
pthread_t tidp;
int error;
int test=4;
int *attr=&test;
error=pthread_create(&tidp,NULL,create,(void *)attr);
if(error!=0)
...{
printf("pthread_create is created is not created ... ");
return -1;
}
sleep(1);
printf("pthread_create is created is created ... ");
return 0;
}
参考 1 http://blog.youkuaiyun.com/zhangwenjianqin/article/details/6415877
参考 2 http://www.cnblogs.com/china-victory/archive/2012/11/09/2763187.html