#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <pthread.h>
#include <semaphore.h>

#define N 3

// Struttura di un nodo della coda thread-safe
typedef struct node {
    int value;
    struct node *next;
} node;

// Struttura della coda thread-safe (usa una linked list)
typedef struct queue_t {
    node *front;
    node *prev;
    //dispatch_semaphore_t mutex;
    //dispatch_semaphore_t popsem;
    sem_t mutex;
    sem_t popsem;
} Queue;

Queue *queue;

// crea una coda vuota
Queue* qcreate()
{
    // crea la coda
    Queue *queue = malloc(sizeof(Queue));

    // inizializza la coda
    queue->front = NULL;
    queue->prev  = NULL;
    sem_init(&queue->mutex, 0, 1);
    //dispatch_semaphore_t *mut = &queue->mutex;
    //*mut = dispatch_semaphore_create(1);
    sem_init(&queue->mutex, 0, 0);
    //dispatch_semaphore_t *sem = &queue->popsem;
    //*sem = dispatch_semaphore_create(0);
    return queue;
}

// Inserisce un elemento nella coda
void qpush(Queue* queue, int value, int npers)
{
    //dispatch_semaphore_wait(queue->mutex, DISPATCH_TIME_FOREVER);
    sem_wait(&queue->mutex);
    printf("Sono %d e ho il mutex\n", npers);

    // creazione di un nuovo nodo
    node *temp = malloc(sizeof(struct node));
    temp->value = value;
    temp->next  = NULL;

    // verifico se la coda è vuota
    if (queue->front == NULL) {
        //in questo caso front e prev coincidono
        queue->front = temp;
        queue->prev  = temp;
        printf("Inserisco nella coda il valore: %d, e faccio post su popsem\n", value);
        sem_post(&queue->popsem);
        //dispatch_semaphore_signal(queue->popsem);
    }
    else {
        //aggiunta di un elemento
        node *old_prev = queue->prev;
        old_prev->next = temp;
        queue->prev = temp;
        printf("Inserisco nella coda il valore: %d\n", value);
    }

    sem_post(&queue->mutex);
    printf("Sono %d e ho lasciato il mutex\n", npers);
    //dispatch_semaphore_signal(queue->mutex);
}

// Estrae un elemento dalla coda
void qpop(Queue* queue, int *value, int npers)
{
    sem_wait(&queue->mutex);
    printf("Sono %d e ho il mutex\n", npers);
    //dispatch_semaphore_wait(queue->mutex, DISPATCH_TIME_FOREVER);

    // verifico se la coda è vuota
    node *front = queue->front;

    if (front != NULL) {
        // lettura del valore ed cancellazione dell'elemento dalla coda
        *value = front->value;
        queue->front = front->next;
        free(front);
        printf("Estraggo dalla coda il valore: %d\n", *value);
        //sem_post(&queue->popsem);
        //dispatch_semaphore_signal(queue->popsem);
    } else {
        printf("la coda è vuota, mi blocco:\n");
    }
    sem_post(&queue->mutex);
    printf("Sono %d e ho lasciato mutex\n", npers);
    //dispatch_semaphore_signal(queue->mutex);
    sem_wait(&queue->popsem);
    //dispatch_semaphore_wait(queue->popsem, DISPATCH_TIME_FOREVER);
}

void qdestroy (Queue* queue){
    sem_destroy(&queue->mutex);
    sem_destroy(&queue->popsem);
    free(queue);
}
void *persona(void *arg){
    int numeropersona = *(int *)arg;
    int info;
    int infoo;
    for (int i = 0; i < N; i++)
    {
        int fval = rand()%10 + 1;
        int sval = rand()%10 + 1;
//        printf("Sono persona %d e voglio inserire %d\n", numeropersona, fval);
        qpush(queue, fval,numeropersona);
        qpop(queue, &info, numeropersona);
//        printf("Sono persona %d e ho estratto %d\n", numeropersona, info);
        qpop(queue, &infoo, numeropersona);
//        printf("Sono persona %d e ho estratto2 %d\n", numeropersona, infoo);
//        printf("Sono persona %d e voglio inserire %d\n", numeropersona, sval);
        qpush(queue, sval, numeropersona);
    }

    pthread_exit(0);
}


int main(){
    pthread_attr_t a;
    pthread_t persone[N];
    int numeropersona[N];

    queue = qcreate();
    printf("Coda creata\n");

    pthread_attr_init(&a);

    for(int i=0; i < N; i++){
        numeropersona[i] = i;
        printf("Sto per creare il thread %d-esimo persona\n", numeropersona[i]);
        pthread_create(&persone[i], &a, persona, &numeropersona[i]);
    }

    for(int i=0; i < N; i++){
        void *ret;
        pthread_join(persone[i], &ret);
    }
    qdestroy(queue);

    return 0;
} 

C Language online compiler

Write, Run & Share C Language code online using OneCompiler's C online compiler for free. It's one of the robust, feature-rich online compilers for C language, running the latest C version which is C18. Getting started with the OneCompiler's C editor is really simple and pretty fast. The editor shows sample boilerplate code when you choose language as 'C' and start coding!

Read inputs from stdin

OneCompiler's C online editor supports stdin and users can give inputs to programs using the STDIN textbox under the I/O tab. Following is a sample C program which takes name as input and print your name with hello.

#include <stdio.h>
int main()
{
    char name[50];
    printf("Enter name:");
    scanf("%s", name);
    printf("Hello %s \n" , name );
    return 0;
    
}

About C

C language is one of the most popular general-purpose programming language developed by Dennis Ritchie at Bell laboratories for UNIX operating system. The initial release of C Language was in the year 1972. Most of the desktop operating systems are written in C Language.

Key features:

  • Structured Programming
  • Popular system programming language
  • UNIX, MySQL and Oracle are completely written in C.
  • Supports variety of platforms
  • Efficient and also handle low-level activities.
  • As fast as assembly language and hence used as system development language.

Syntax help

Loops

1. If-Else:

When ever you want to perform a set of operations based on a condition if-else is used.

if(conditional-expression) {
   // code
} else {
   // code
}

You can also use if-else for nested Ifs and if-else-if ladder when multiple conditions are to be performed on a single variable.

2. Switch:

Switch is an alternative to if-else-if ladder.

switch(conditional-expression) {    
case value1:    
 // code    
 break;  // optional  
case value2:    
 // code    
 break;  // optional  
...    
    
default:     
 // code to be executed when all the above cases are not matched;    
} 

3. For:

For loop is used to iterate a set of statements based on a condition.

for(Initialization; Condition; Increment/decrement){  
  // code  
} 

4. While:

While is also used to iterate a set of statements based on a condition. Usually while is preferred when number of iterations are not known in advance.

while(condition) {  
 // code 
}  

5. Do-While:

Do-while is also used to iterate a set of statements based on a condition. It is mostly used when you need to execute the statements atleast once.

do {
  // code 
} while (condition); 

Arrays

Array is a collection of similar data which is stored in continuous memory addresses. Array values can be fetched using index. Index starts from 0 to size-1.

Syntax

One dimentional Array:

data-type array-name[size];

Two dimensional array:

data-type array-name[size][size];

Functions

Function is a sub-routine which contains set of statements. Usually functions are written when multiple calls are required to same set of statements which increases re-usuability and modularity.

Two types of functions are present in C

  1. Library Functions:

Library functions are the in-built functions which are declared in header files like printf(),scanf(),puts(),gets() etc.,

  1. User defined functions:

User defined functions are the ones which are written by the programmer based on the requirement.

How to declare a Function

return_type function_name(parameters);

How to call a Function

function_name (parameters)

How to define a Function

return_type function_name(parameters) {  
  //code
}