Home > Backend Development > C++ > Infinite printing 1 2 3 using threads in C language

Infinite printing 1 2 3 using threads in C language

WBOY
Release: 2023-08-29 08:17:02
forward
1151 people have browsed it

使用C语言的线程无限打印1 2 3

Here we need to repeatedly print the 1 2 3 sequence infinite times using threads in C programming language.

Let’s take a look at the sample output of our code:

1 2 3 1 2 3 1 2 3 1 2 3

For this we will need to use three Threads running in parallel in C programming language. You also need a variable that is initialized to 1 in the first thread and has its value updated based on its previous value. Then run an infinite loop inside the function.

Example

Let's look at the program that implements our solution:

#include <stdio.h>
#include <pthread.h>
pthread_cond_t cond1 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond2 = PTHREAD_COND_INITIALIZER;
pthread_cond_t cond3 = PTHREAD_COND_INITIALIZER;
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
int value = 1;
void *foo(void *n){
   while(1) {
      pthread_mutex_lock(&lock);
      if (value != (int)*(int*)n) {
         if ((int)*(int*)n == 1) {
            pthread_cond_wait(&cond1, &lock);
         } else if ((int)*(int*)n == 2) {
            pthread_cond_wait(&cond2, &lock);
         } else {
            pthread_cond_wait(&cond3, &lock);
         }
      }
      printf("%d ", *(int*)n);
      if (value == 3) {
         value = 1;
         pthread_cond_signal(&cond1);
      }
      else if(value == 1) {
         value = 2;
         pthread_cond_signal(&cond2);
      } else if (value == 2) {
            value = 3;
            pthread_cond_signal(&cond3);
      }
      pthread_mutex_unlock(&lock);
   }
   return NULL;
}
int main(){
   pthread_t tid1, tid2, tid3;
   int n1 = 1, n2 = 2, n3 = 3;
   pthread_create(&tid1, NULL, foo, (void *)&n1);
   pthread_create(&tid2, NULL, foo, (void *)&n2);
   pthread_create(&tid3, NULL, foo, (void *)&n3);
   while(1);
   return 0;
}
Copy after login

Output

1 2 3 1 2 3 1 2 3 1 2 3 1 2 3&hellip;.
Copy after login

The above is the detailed content of Infinite printing 1 2 3 using threads in C language. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template