Untitled

 avatar
unknown
plain_text
16 days ago
957 B
3
Indexable
#include<stdio.h>
#include<stdlib.h>
#include<pthread.h>
#include<semaphore.h>
#define MAX_PORTS 5
sem_t port_semaphore;
void* open_port(void* arg)
{
 if(sem_wait(&port_semaphore) == 0)
 {
  int thread_id = *((int*)arg);
  printf("Thread %d:port is open.\n", thread_id);
  sleep(2);
  printf("Thread %d:port is closed.\n",thread_id);
  sem_post(&port_semaphore);
 }
else
{
 printf("Thread %d: could not open a port,semaphore wait failed.\n",*((int*)arg));
 }
return NULL;
}
int main()
{
 int i=0;
 if(sem_init(&port_semaphore,0,MAX_PORTS) !=0)
 {
  perror("semaphore initilization failed");
  return -1;
 }
pthread_t threads[10];
int thread_ids[10];
for(i=0;i<10;i++)
{
 thread_ids[i]=i+1;
 if(pthread_create(&threads[i],NULL,open_port,&thread_ids[i]) !=0)
{
 perror("Thread creation failed");
 return -1;
}
 for(i=0;i<10;i++)
{
 pthread_join(threads[i],NULL);
}
 sem_destroy(&port_semaphore);
 return 0;
}
}
Editor is loading...
Leave a Comment