有了线程,程序必须根据其优先级(从0到10)打印线程。
线程是在程序内部运行的轻量级进程。一个简单的程序可以包含n个线程。
与Java不同,语言标准不支持多线程,POSIX线程(Pthread)是C / C ++中多线程使用的标准。C不包含对多线程应用程序的任何内置支持。相反,它完全依赖于操作系统来提供此功能。
要使用线程函数,我们使用头文件#include。该头文件将包含程序中与线程相关的所有函数,例如pthread_create()等。
现在的任务是使用gcc编译器附带的pthread标准库同步n个线程。这个想法是取线程数并在第一线程中打印1,在第二线程中打印2,在第三线程中打印3直到第十线程。根据线程的优先级,输出将包含从1到10的数字。
Start Step 1 -> Declare global variables as int MAX=10 and count=1 Step 2 -> declare variable thr of pthread_mutex_t and cond of pthread_cond_t Step 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
#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