使用C语言中的线程同步顺序打印数字。
给定线程,程序必须根据从0到10的优先级打印线程。
什么是线程?
线程是在程序内运行的轻量级进程。一个简单的程序可以包含n个线程。
与Java不同,多线程不受语言标准的支持,POSIX线程(Pthreads)是C/C++中多线程使用的标准。C语言本身并不包含对多线程应用程序的任何内置支持,而是完全依赖操作系统提供此功能。
它在我们的程序中是如何工作的?
要使用线程函数,我们使用头文件#include <pthread.h>。此头文件将包含程序中与线程相关的全部函数,例如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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP