给定线程,程序必须根据它们的优先级从0到10打印线程。
什么是线程?线程是在程序内部运行的轻量级进程。一个简单的程序可以包含n个线程。
与java不同,c/c++语言标准不支持多线程,posix线程(pthreads)是c/c++中多线程的标准。c语言不包含任何内置的多线程应用程序支持,而是完全依赖于操作系统来提供此功能。
在我们的程序中如何工作?为了使用线程函数,我们使用头文件#include。这个头文件将包含我们程序中与线程相关的所有函数,如pthread_create()等。
现在的任务是使用gcc编译器提供的pthread标准库来同步n个线程。思路是获取线程计数并在第一个线程中打印1,在第二个线程中打印2,在第三个线程中打印3,直到第十个线程。输出将根据线程的优先级包含从1到10的数字。
算法startstep 1 -> declare global variables as int max=10 and count=1step 2 -> declare variable thr of pthread_mutex_t and cond of pthread_cond_tstep 3 -> declare function void *even(void *arg) loop while(count < max) call pthread_mutex_lock(&thr) loop while(count % 2 != 0) call pthread_cond_wait(&cond, &thr) end print count++ call pthread_mutex_unlock(&thr) call pthread_cond_signal(&cond) end call pthread_exit(0)step 4 -> declare function void *odd(void *arg) loop while(count < max) call pthread_mutex_lock(&thr) loop while(count % 2 != 1) call pthread_cond_wait(&cond, &thr) end print count++ call pthread_mutex_unlock(&thr) call pthread_cond_signal(&cond) end set pthread_exit(0)step 5 -> in main() create pthread_t thread1 and pthread_t thread2 call pthread_mutex_init(&thr, 0) call pthread_cond_init(&cond, 0) call pthread_create(&thread1, 0, &even, null) call pthread_create(&thread2, 0, &odd, null) call pthread_join(thread1, 0) call pthread_join(thread2, 0) call pthread_mutex_destroy(&thr) call pthread_cond_destroy(&cond)stop
example的中文翻译为:示例#include <pthread.h>#include <stdio.h>#include <stdlib.h>int max = 10;int count = 1;pthread_mutex_t thr;pthread_cond_t cond;void *even(void *arg){ while(count < max) { pthread_mutex_lock(&thr); while(count % 2 != 0) { pthread_cond_wait(&cond, &thr); } printf("%d ", count++); pthread_mutex_unlock(&thr); pthread_cond_signal(&cond); } pthread_exit(0);}void *odd(void *arg){ while(count < max) { pthread_mutex_lock(&thr); while(count % 2 != 1) { pthread_cond_wait(&cond, &thr); } printf("%d ", count++); pthread_mutex_unlock(&thr); pthread_cond_signal(&cond); } pthread_exit(0);}int main(){ pthread_t thread1; pthread_t thread2; pthread_mutex_init(&thr, 0); pthread_cond_init(&cond, 0); pthread_create(&thread1, 0, &even, null); pthread_create(&thread2, 0, &odd, null); pthread_join(thread1, 0); pthread_join(thread2, 0); pthread_mutex_destroy(&thr); pthread_cond_destroy(&cond); return 0;}
输出如果我们运行上述程序,它将生成以下输出
1 2 3 4 5 6 7 8 9 10
以上就是使用c程序进行线程同步,按顺序打印数字的详细内容。