linux程序设计——同时执行的线程(第十二章)

来源:互联网 发布:三国志11公孙瓒数据 编辑:程序博客网 时间:2024/05/01 11:09

12.4    同时执行

接下来编写一个程序来验证两个线程的执行是同时执行的(当然,如果是在一个单处理器系统上,线程的同时执行就需要靠CPU在线程之间的快速切换来实现).这个程序中,在两个线程之间使用轮询技术,所以效率很低,同时程序还有利用这一事实,即除局部变量之外,所有其他变量都将在一个进程中的所有线程之间共享.
编写程序thread2.c,在thread1.c上增加了另外一个文件范围变量来测试哪个线程正在执行.
/************************************************************************* > File Name:    thread2.c > Description:  thread2.c函数在thread1.c的基础上,增加了一个文件范围变量run_now来测试哪个线程正在运行 > Author:       Liubingbing  > Created Time: 2015年07月05日 星期日 13时06分35秒 > Other:        thread2.c程序是在两个线程之间使用轮询技术,因此它的效率很低     thread2.c中每个线程通过设置run_now变量的方法来通知另一个线程开始运行,然后,它会等待另一个线程改变这个变量的值后再次运行.     这个例子显示了两个线程之间自动交替执行,同时,两个线程共享run_now变量. ************************************************************************/#include <stdio.h>#include <unistd.h>#include <stdlib.h>#include <string.h>#include <pthread.h>void *thread_function(void *arg);char message[] = "hello world";int run_now = 1;int main(){int res;pthread_t a_thread;void *thread_result;int print_count1 = 0;res = pthread_create(&a_thread, NULL, thread_function, (void *)message);if (res != 0){perror("Thread creation failed");exit(EXIT_FAILURE);}while(print_count1 < 20){if (run_now == 1){printf("1");run_now = 2;}else{sleep(1);}print_count1++;}printf("\nWaiting for thread to finish...\n");res = pthread_join(a_thread, &thread_result);if (res != 0){perror("Thread join failed");exit(EXIT_FAILURE);}printf("Thread joined\n");exit(EXIT_SUCCESS);}void *thread_function(void *arg){int print_count2 = 0;while (print_count2 < 20){if (run_now == 2){printf("2");run_now = 1;}else{sleep(1);}print_count2++;}sleep(3);}
编译后运行后结果如下所示:

在main中设置run_now为1,在执行新线程时将其设置为2,在while循环中不断地来检查等待它的值,这种方式称为忙等待.运行的结果说明两个线程之间自动交替执行.
0 0
原创粉丝点击