使用C程序进行线程同步,按顺序打印数字

王林
王林 转载
2023-08-26 22:45:06 908浏览

使用C程序进行线程同步,按顺序打印数字

给定线程,程序必须根据它们的优先级从0到10打印线程。

什么是线程?

线程是在程序内部运行的轻量级进程。一个简单的程序可以包含n个线程。

与Java不同,C/C++语言标准不支持多线程,POSIX线程(Pthreads)是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

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程序进行线程同步,按顺序打印数字的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除