Untitled
unknown
plain_text
8 months ago
1.1 kB
5
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 initialization failed");
return -1;
}
pthread_t threads[10];
int thread_ids[10];
for (i = 0; i < 10; i++)
{
thread_ids[i] = i + 1; // Assign thread ids starting from 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