问题:
最近把以前的代码又review了下,发现原来的多线程demo程序竟然没得到如我预期的执行效果,即pthread_create创建线程成功,但是没有执行对应线程的函数。后来发现是pthread的创建似乎会延迟一些时间,在pthread_create里对应的线程函数运作之前,主程序(主线程)就已经结束了,当然看起来就像没运作一样。
解决方法:
在pthread_create后加一句sleep(1),让主程序在此阻塞一秒
更好的方法:对于多线程编程,主线程在创建线程后应该调用pthread_join( )函数,等待子线程执行完后再结束主线程。
对比如下
线程一加了sleep(1),线程二未加sleep(1)
/*********************************************************************************
* Copyright: (C) 2018 Wang Tao
* All rights reserved.
*
* Filename: thread.c
* Description: This file
*
* Version: 1.0.0(2018年05月15日)
* Author: wang tao <TAlicer@163.com>
* ChangeLog: 1, Release initial version on "2018年05月15日 00时34分04秒"
*
********************************************************************************/
#include <pthread.h>
#include <stdio.h>
/*线程一*/
void *thread_worker1(void *args) //参数为void *类型的函数可以接受任意一种类型的指针
{
printf("thread worker1 [%lu] print %s\n\n",pthread_self(),(char *)args); //pthread_self:获取自己的线程ID
}
/* 线程二*/
void *thread_worker2(void *args)
{
printf("thread worker2 [%lu] print %s\n",pthread_self(),(char *)args);
}
/********************************************************************************
* Description:
* Input Args:
* Output Args:
* Return Value:
********************************************************************************/
int main (int argc, char **argv) //写多线程的程序,编译时一定要链接线程的动态库(gcc thread.c -lpthread )
{
pthread_t tid1;
pthread_t tid2;
pthread_create(&tid1,NULL,thread_worker1,"cat"); //pthread_create:创建一个线程来执行一个函数
printf("start thread_worker1 [%lu]\n",tid1);
sleep(1); 主线程在此阻塞一秒
pthread_create(&tid2,NULL,thread_worker2,"dog");
printf("start thread_worker2 [%lu]\n",tid2);
return 0;
} /* ----- End of main() ----- */