linux下的系统编程--线程

//线程共享进程空间
#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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hmbbPdx_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值