最近学习linux多线程,对执行过程一直不是很熟悉。现就对所学进行总结,以备后用。
以下是一段程序代码:
//编译 gcc -o thread.c thread -lpthread #include
#include //exit所需的
#include
void thread1(void)
{
int i=0;
for(i=0;i<6;i++)
{
printf("This is a
pthread1.\n");
if(i==2)
pthread_exit(0);
sleep(1);
void thread2(void)
{
int i;
for(i=0;i<3;i++)
{
printf("This is a pthread2.\n");
sleep(1);
}
pthread_exit(0);
}
int main(void)
{
pthread_t id1,id2;
int i,ret;
ret=pthread_create(&id1,NULL,(void *)
thread1,NULL);
if(ret!=0)
{
printf ("Create pthread
error!\n");
exit (1);
}
sleep(1); //@3 ret=pthread_create(&id2,NULL,(void
*) thread2,NULL);
if(ret!=0)
{
printf ("Create pthread
error!\n");
exit (1);
}
pthread_join(id1,NULL); //@4 pthread_join(id2,NULL);
//@4
printf ("Main pthread will exit!\n");
exit (0);
}
1、将@1、@2、@3、@4全部去掉(//)后 ./thread
Main pthread will exit!
子线程无输出。
说明:创建的两个线程成功了却没有被执行。
2、将@1、@2、@4全部去掉(//)后 ./thread
This is a pthread1.
This is a pthread1.
This is a pthread1.
Main pthread will exit!
说明:结合1,主线程在thread1创建后休眠1s,thread1被执行了,thread2没有。
3、将@1、@2、@3去掉(//)后 ./thread
This is a pthread2.
This is a pthread2.
This is a pthread2.
This is a pthread1.
This is a pthread1.
This is a pthread1.
Main pthread will exit!
说明:创建的线程thread1、thread2都被执行了,但是thread2先执行。
总结1:从1、2、3可以看出pthread_join起到等待(阻塞)的作用,所等待线程未返回前阻塞main继续执行。被阻塞的情况下,未执行的线程中后发起的线程先执行;所有子线程执行都在主线程空闲状态下。
4、将@1、@2去掉(//)后 ./thread
This is a pthread1.
This is a pthread1.
This is a pthread1.
This is a pthread2.
This is a pthread2.
This is a pthread2.
Main pthread will exit!
说明:主线程在thread1创建后休眠1s,thread1先被执行了,thread2后执行。
5、将@3去掉(//)后 ./thread
This is a pthread2.
This is a pthread1.
This is a pthread2.
This is a pthread1.
This is a pthread2.
This is a pthread1.
Main pthread will exit!
说明:被创建的子线程空闲时(sleep)执行别的子线程,没有空闲则子线程执行完后转到其他子线程执行。
总结:综上可以看出:1、创建的子线程没有对应的pthread_join函数,则主线程没有空闲就不执行子线程,有空闲就执行等待执行的子线程(最后创建的最先执行),主线程空闲时间结束时子线程没有处理完也不再执行。
2、创建的子线程有对应的pthread_join函数,则该子线程与子线程之间执行顺序按照后创建先执行,与主线程关系为主线程空闲则执行,若主线程不空闲,则一直阻塞到pthread_join函数时执行。