In: Computer Science
Modify the following source code so that five subsequent threads print the message “Hello World number,” where number indicates the unique thread created; e.g. “Hello World 1”
// Your_name_goes_here
#include <pthread.h>
#include <semaphore.h>
sem_t semaphore; // also a global variable just like mutexes
void *thread_function( void *arg )
{
sem_wait( &semaphore );
// perform some task
pthread_exit( NULL );
}
int main()
{
int tmp; tmp = sem_init( &semaphore, 0, 0 ); // initialize
pthread_create( &thread[i], NULL, thread_function, NULL
);
sem_post( &semaphore );
pthread_join( thread[i], NULL );
sem_destroy( &semaphore );
return 0;
}
Here is the code,
#include <pthread.h>
#include <semaphore.h>
#include <iostream>
using namespace std;
sem_t semaphore; // also a global variable just like mutexes
void *thread_function( void *arg ) {
    sem_wait( &semaphore );
    long number;
    number = (long) arg;
    cout<<"Hello World "<<number<<endl;
    pthread_exit( NULL );
}
int main() {
    int tmp; 
    tmp = sem_init( &semaphore, 0, 0 ); // initialize
    pthread_t threads[5];
    for(int i=1; i<=5; i++){
        pthread_create( &threads[i], NULL, thread_function, (void *)i);
        sem_post( &semaphore );
        pthread_join( threads[i], NULL );
        sem_destroy( &semaphore );
    }
    return 0;
}
OUTPUT:

If you have any doubts then put in the comments. Also, do upvote the solution.