线程优先级学习笔记

刚刚学习线程,有一点记录一点。

#include <pthread.h>
#include <stdio.h>
 
pthread_mutex_t mutex ;
void *print_msg(void *arg){
        int i=0;
		printf("this is %d\n",(int*)arg);
        pthread_mutex_lock(&mutex);
        for(i=0;i<3;i++){
                printf("output %d: %d\n",(int*)arg, i);
                //sleep(1);
        }
        pthread_mutex_unlock(&mutex);
}
int main(int argc,char** argv){
        pthread_t id1;
        pthread_t id2, id0;
        pthread_mutex_init(&mutex,NULL);
        pthread_create(&id2,NULL,print_msg,(void*)2);
        pthread_create(&id1,NULL,print_msg,(void*)1);
	pthread_create(&id0,NULL,print_msg,(void*)0);
        pthread_join(id2,NULL);
        //pthread_join(id1,NULL);
        pthread_mutex_destroy(&mutex);
        return 1;
}

运行结果为:

this is 0
output 0: 0
output 0: 1
output 0: 2
this is 1
output 1: 0
output 1: 1
output 1: 2
this is 2
output 2: 0
output 2: 1
output 2: 2
 

一开始是很疑惑,为什么怎么改pthread_join的顺序,都是先运行0,pthread_join不是把当前线程阻塞,等待子线程运行完吗,那先运行哪个不是看pthread_join的顺序么。

后来改了下pthread_create的顺序,发现是先创建的,最后运行,查了下原来是按默认的线程优先级,后创建的优先级高。

pthread_join是阻塞当前线程,按照刚才的思路,我就把pthread_join改为id1,果然,id2那部分就不会打印出来,因为优先级低于1,系统主线程只会阻塞到id1结束。

发布了13 篇原创文章 · 获赞 0 · 访问量 384

猜你喜欢

转载自blog.csdn.net/tjw316248269/article/details/104648298