76 248
Assignments Done
Successfully Done
In May 2019

Answer to Question #22080 in C++ for niloofar

Question #22080
How to write a program that increasingly and every once in a second prints 1 integer variable in 2 separate threads(using multithreading)?
Expert's answer
#include <conio.h>
#include <iostream>

#include <windows.h>
#include <pthread.h>

#define sleep Sleep

using namespace std;

const int max_number = 16;

int number;
/* Use mutex to prevent the simultaneous access to the number variable
from different threads */
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

void* print_number(void* arg)
while (number < max_number)
cout << number << endl;

return NULL;

int main(void)
pthread_t thread_1;
pthread_t thread_2;

number = 0; //initialize integer variable
pthread_create(&thread_1, NULL, &print_number, NULL); & //create 1st thread
pthread_create(&thread_2, NULL, &print_number, NULL); & //create 2nd thread

pthread_join(thread_1, NULL); //waiting for the 1st thread
pthread_join(thread_2, NULL); //wait for the 2nd thread exit

return 0;

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!


No comments. Be first!

Leave a comment

Ask Your question

Privacy policy Terms and Conditions