//线程共享进程空间
#include <stdio.h>
#include <string.h>
#include <pthread.h>
int temp=111;
void sayHello(void)
{
int temp;
printf("thread id:%p Hello &temp:%p\n",pthread_self(),&temp);
sleep(5);
}
//线程启动例程:该线程在这个函数开始 该函数结束线程也结束
void *threadWork(void *arg)
{
printf("new pthread runing arg:%d id:%p temp:%d\n",*(int *)arg,pthread_self(),temp);
sayHello();
sleep(2);
*(int *)arg=888;
temp=222;
printf("new pthread change temp:%d\n",temp);
printf("new pthread over\n");
return (void *)0;//pthread_exit((void *)0);
}
int main(void)
{
int ret,value=555;
pthread_t tid;
printf("&value:%p temp:%d\n",&value,temp);
//尽量不要打印线程号,不同平台实现有所区别 所以移植性差
printf("main pid:%d main thread id:%p\n",getpid(),pthread_self());
//create new pthread
//ret=pthread_create(&tid,NULL,threadWork,NULL);
ret=pthread_create(&tid,NULL,threadWork,&value);//创造线程tid为线程的tid,threadWork线程函数,value线程参数;
if(ret!=0)//error
{
printf("create pthread error:%s\n",strerror(ret));
return 1;
}
//
sayHello();
pthread_join(tid,NULL); //阻塞等待线程结束
printf("main value:%d temp:%d\n",value,temp);
return 0;
}
由于线程并不是linux的标准库,所以在编译的时候需要加-lpthread,链接上线程库,例如:gcc * -lpthread