60 721
Assignments Done
97,9%
Successfully Done
In April 2018

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)
{
pthread_mutex_lock(&mutex);
cout << number << endl;
number++;

sleep(1000);
pthread_mutex_unlock(&mutex);
}
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

getch();
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!

Comments

No comments. Be first!

Leave a comment

Ask Your question

Submit
Privacy policy Terms and Conditions