使用pthread创建一个线程,可以使用这个线程来完成耗时任务,解决并发问题。
#include<pthread.h>
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
struct stu
{
int id;
char name[32];
};
void *fun(void *arg)
{
int i=0;
struct stu *p=(struct stu *)arg;
printf("id:%d name:%s\n",p->id,p->name);
free(p);
while(1)
{
i++;
printf("thread run\n");
sleep(2);
if(i==5)
{
printf("pthread over\n");
pthread_exit(NULL);
}
}
}
int main()
{
int ret;
pthread_t p1;
struct stu s={1,"zhangshan"};
struct stu *p;
p=malloc(sizeof(struct stu));
*p=s;//申请新的空间存放数据s,保障s改变不影响后面
printf("main run\n");
ret=pthread_create(&p1,NULL,fun,(void *)p);
if(ret<0)
{
printf("pthread error\n");
}
while(1)
{
printf("main thread run\n");
sleep(2);
}
}