linux下线程的创建和管理

35 篇文章 0 订阅
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<string.h>
char msg[]="Hello";
void* thread_function(void*);
int main()
{
    int res=-1;
    pthread_t th={0};
    printf("the mem is %s\n",msg);
    res=pthread_create(&th,NULL,thread_function,(void*)msg);
    if(0!=res)
    {
        printf("sorry the thread create failed\n");
        exit(0);
    }
    //开始合并线程,也即等待线程执行完之后才能继续向下执行,thread_res是pthread_exit中的值
    void* thread_res=NULL;
    res=pthread_join(th,&thread_res);
    if(0!=res)
    {
        printf("thread_join failed \n");
        exit(0);
    }
    printf("thread exit successfully!the return is :%s\n",(char*)thread_res);
    printf("the mem is %s\n",msg);
    exit(0);
    return 0;
}
void* thread_function(void* msg)
{
    printf("this is thread output\n");
    //休眠3秒
    sleep(3);
    strcpy((char*)msg,"youto");
    pthread_exit("线程执行完毕");
}

恩,恩,还有对应的makefile文件如下:

test: thread.o
	gcc -o test thread.o  -lpthread
thread.o:thread.c
	gcc -c thread.c
clean:
	rm test *.o


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

世纪殇

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

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

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

打赏作者

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

抵扣说明:

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

余额充值