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)?
1
Expert's answer
2013-01-15T08:49:27-0500
#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 the first!

Leave a comment

LATEST TUTORIALS
APPROVED BY CLIENTS