1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| #include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include "pthread.h"
#include "semaphore.h"
sem_t psem_for_rx;
sem_t psem_for_tx;
void* print_rx_frames(void* pParameters)
{
puts("THREAD FOR RX");
for(int i = 0; i < 0xF; i++)
{
// Wait until it is our turn to write
sem_wait(&psem_for_rx);
// Write our RX frame
printf("Receive %d...\n", i);
// Let TX thread know that it can write
sem_post(&psem_for_tx);
}
return pParameters;
}
void* print_tx_frames(void* pParameters)
{
puts("THREAD FOR TX");
for(int i = 0; i < 0xF; i++)
{
// Wait until it is our turn to write
sem_wait(&psem_for_tx);
// Write our TX frame
printf("Send %d...\n", i);
// Let RX thread d know that it can write
sem_post(&psem_for_rx);
}
return pParameters;
}
int main()
{
pthread_t thread_rx;
pthread_t thread_tx;
puts("Try to create a thread...");
sem_init(&psem_for_tx, 0, 1);
sem_init(&psem_for_rx, 0, 0);
int rx_created = pthread_create(&thread_rx, NULL, print_rx_frames, NULL);
int tx_created = pthread_create(&thread_tx, NULL, print_tx_frames, NULL);
if(rx_created == 0 && tx_created == 0)
{
pthread_join(thread_rx, NULL);
pthread_join(thread_tx, NULL);
printf("Thread RX (%d) and thread TX (%d) terminated\n", thread_rx, thread_tx);
}
else
{
printf("Error while one thread\n");
}
return 0;
} |
Partager