上一节中,从输出的数字分布,可以看出是代码多线程轮流执行的,但是我们并不知道对应数字是哪一个线程输出的,这一节我们通过学习往线程中传参数 ,以此区分线程。
完整代码如下:
#include <stdio.h>
#include<stdlib.h>
#include<pthread.h>
void* test(void* args) //传入的参数是 Void *类型
{
int i;
char* name=(char*)args;//转换类型
for(i=0;i<5000;i++)
printf("%s:%-6d",name,i);
return NULL;
}
int main()
{
pthread_t th2;
pthread_t th1;
pthread_create(&th1,NULL,test,"th1");//第四个参数:输出字符串th
pthread_create(&th2,NULL,test,"th2");
pthread_join(th1,NULL);//等待线程TH执行完
pthread_join(th2,NULL);//等待线程TH1执行完
printf("\n");
return