linux下线程的创建和等待

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
char message[]="hello world ";
void *thread_function(void *arg)//线程函数
{
   printf("thread_function is running, Argument is %s\n",(char *)arg);
   sleep(3);
   strcpy(message,"Bye!");
   pthread_exit("Thank you for the cpu time");//注意线程退出函数
}

int main()
{
  int res;
  pthread_t a_thread; //新线程的标识符
  void *thread_result;//定义一个线程返回值
  res=pthread_create(&a_thread,NULL,thread_function,(void *)message);//创建线程
  if(res!=0)//线程创建不成功
    {
     perror("Thread create error!");
     exit(EXIT_FAILURE);
    }
  printf("waiting for thread to finish...\n");
  res=pthread_join(a_thread,&thread_result);//等待新线程结束
  if(res!=0)
   {
     perror("Thread join error!");
     exit(EXIT_FAILURE);
    }
  printf("Thread joined , it returned %s\n",(char *)thread_result);
  printf("Message is now %s\n",message);
  exit(EXIT_SUCCESS);
}

注意,多线程的编译和普通程序的编译是不一样的,要用这样的命令: 【cc -D_REENTRANT thread.c -g -o thread -lpthread】

大家可以看到,全局变量message经过线程创建函数传递给线程函数后由【hello world】变成了【Bye!】

 res=pthread_join(a_thread,&thread_result);//等待新线程结束
等待新线程结束,只有新线程结束后才会向下执行。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值