#include <pthread.h> #include <iostream> using namespace std; void *PrintHello(v
ID: 3882266 • Letter: #
Question
#include <pthread.h>
#include <iostream>
using namespace std;
void *PrintHello(void *arg)
{
int actual_arg = *((int*) arg);
cout << "Hello World from thread with arg: " << actual_arg << "! ";
return 0;
}
int main()
{
pthread_t id;
int rc;
cout << "In main: creating thread ";
int t = 23;
rc = pthread_create(&id, NULL, PrintHello, (void*) &t);
if (rc){
cout << "ERROR; return code from pthread_create() is " << rc << std::endl;
return -1;
}
pthread_exit(0);
}
Explanation / Answer
#include <pthread.h>
#include <iostream>
using namespace std;
// passing integer as argument
void *PrintHello(void *threadid)
{
int id = *((int*) threadid);
cout << "Hello World from thread with arg: " << id << "! ";
return 0;
}
int main()
{
pthread_t id;
int rc,t;
cout << "In main: creating thread ";
//user input
cout<< "Enter the Number: ";
//read user input from console
cin>>t;
rc = pthread_create(&id, NULL, PrintHello, (void*) &t);
if (rc){
cout << "ERROR; return code from pthread_create() is " << rc << std::endl;
return -1;
}
pthread_exit(0);
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.