线程的创建:
int pthread_create(pthread_t *tidp,const pthread_attr_t *attr,void *(*start_rtn)(void*),void *arg);
头文件:
#include<pthread.h>
返回值:
若线程创建成功,则返回0。若线程创建失败,则返回出错编号
例子:
Int err = pthread_create(&ntid, NULL, thr_fn, NULL);
if (err != 0)
printf("can't create thread: %s\n", strerror(err));
第一个参数为指向线程标识符的指针。
第二个参数用来设置线程属性。
第三个参数是线程运行函数的起始地址。
最后一个参数是运行函数的参数。
第一步:设置指向线程标识符的指针
pthread_t ntid;
第二步:设置线程属性
第三步:设置函数
void *thr_fn(void * arg)
最后一个参数是运行函数的参数。
:可以传递一个参数
Int rc,t;
rc = pthread_create(&thread[t],NULL,PrintHello,&t);
代码:
#include <stdio.h>
#include <pthread.h>
#include <sys/time.h>
#include <unistd.h>
#include <string.h>
typedef struct
{
char a[255];
int b;
int c;
}num;
void *hello(void *arg)
{
printf("----传递一个结构体----\n");
num num1= *(num*) arg;
num1.b=9;
// num1.a[]={"hello"};//结构体不能如此赋值,报错,只能strcpy
strcpy (num1.a," zhao ");
num1.c=10;
printf("%d,%d,%s\n",num1.b,num1.c,num1.a);
}
void *test(void *arg)
{
printf("----传递一个字符串-----\n");
printf("%s\n",(char*)arg);
}
int main(int argc,const char* argv[])
{
int err;
num word;
char str[]="name";
pthread_t id1,id2;
err=pthread_create(&id1,NULL,hello,&word);//传递结构体
if(err!=0)
{
printf("ddsafsdf");
}
err=pthread_create(&id2,NULL,test,str);//传递字符串
if(err!=0)
{
printf("ddsafsdf");
}
sleep(1);
return 0;
}