LINUX线程同步初探

0x00.什么是线程同步
    同步,又称直接制约关系,是指多个线程(或进程)为了合作完成任务,必须严格按照规定的 某种先后次序来运行


0x01.案例代码

 1 void* PthreadFunc(void* argc);
 2 int flag_num = 1;
 3 
 4 int main(int argc, char* argv[])
 5 {
 6     pthread_t pid;
 7     void* ret_val;
 8 
 9     int create_status = pthread_create(&pid, NULL,  &PthreadFunc, NULL);
10     if(0 != create_status)
11     {      perror("main()->pthread_create error");
12         exit(1);
13     }
14 
15     //input data to public source area
16     for(int i = 0;  i < 10; ++i)
17     {
18         if(flag_num == 1)
19         {
20             printf("1");
21             flag_num = 2;
22         }else{
23             sleep(1);
24         }
25     }
26 
27     int join_status = pthread_join(pid, &ret_val);
28     if(0 != join_status)
29     {
30         perror("main()->pthread_join error");
31         exit(1);
32     }
33 
34     //print array's data
35     for(int i = 0; i < 10; ++i)
36     {
37         printf("%d  ", arr[i]);
38     }
39 
40     return 0;
41 }
42 
43 void* PthreadFunc(void* argc)
44 {
45         if(flag_num == 2)
46         {
47             printf("2");
48             flag_num = 1;
49         }else{
50             sleep(1);
51         }
52 }

 

执行结果:
  reacher@ubuntu:~/projects/proj$ ./syn
  1212121212

结论:利用条件避免无休止抢占公共资源

 

0x02.修改代码获取新知识点 …(⊙_⊙;)

 

 1 void* PthreadFunc(void* argc);
 2 int arr[10];
 3 
 4 int main(int argc, char* argv[])
 5 {
 6     pthread_t pid;
 7     void* ret_val;
 8 
 9     int create_status = pthread_create(&pid, NULL,  &PthreadFunc, NULL);
10     if(0 != create_status)
11     {      perror("main()->pthread_create error");
12         exit(1);
13     }
14 
15     //input data to public source area
16     for(int i = 0;  i < 10; ++i)
17     {
18         arr[i] = i;
19     }
20 
21     int join_status = pthread_join(pid, &ret_val);
22     if(0 != join_status)
23     {
24         perror("main()->pthread_join error");
25         exit(1);
26     }
27 
28     //print array's data
29     for(int i = 0; i < 10; ++i)
30     {
31         printf("%d  ", arr[i]);
32     }
33 
34     return 0;
35 }
36 
37 void* PthreadFunc(void* argc)
38 {
39     for(int i = 0;  i < 10; ++i)
40     {
41         arr[i] = i + 10;
42     }
43 }

 

执行代码结果:
reacher@ubuntu:~/projects/proj$ ./syn
10 11 12 13 14 15 16 17 18 19

  当时出现结果一脸懵,后来查资料发现了线程是有优先级的:main(for()) 属于主线程,PthreadFunc(for())属于子线程、

  主线程的优先级大于子线程,所以main.for()先对arr进行了数据写入,pthread.for()后写入数据,输出结果为线程输入数据

 

posted @ 2017-08-13 12:23  瓜子啊  阅读(162)  评论(0编辑  收藏  举报