Threads and Structures in C


If a thread wants to pass multiple arguments to another thread it creates, it needs to use a structure. Structures are declared in C as follows:

      struct Example
      {
          int my_int;
          char my_char;
          int * my_int_pointer;
      }; 
The piece of code above defines a new datatype, called struct Example. You can now create variables of this type using
      struct Example name_of_variable;
and access fields of the structure using the dot notation:
      name_of_variable.my_int = 5;
      name_of_variable.my_char = 'a';
      name_of_variable.my_int_pointer = &(name_of_variable.my_int);
In case of pointer variables of this type
      struct Example * pointer_variable;
you can access fields of the structure using the arrow operator:
      pointer_variable->my_int = 5;
      pointer_variable->my_char = 'a';
      pointer_variable->my_int_pointer = &(pointer_variable->my_int);

Exercise 1. Compile, run and understand the hellostruct-arr.c pthreads program that illustrates a safe way to pass multiple arguments to threads during thread creation, using arrays of structures.
Exercise 2. Compile, run and understand the hellostruct-ptr.c pthreads program that illustrates a safe way to pass multiple arguments to threads during thread creation, using pointers to structures.
Exercise 3. Here is an incomplete piece of code that implements a solution to the multiple producers-consumers problem. Fill in the missing code to complete the solution.

Sample output:

[P1] Producing 0 ...
[P1] Producing 1 ...
 ------> [C1] Consuming 0 ...
 ------> [C1] Consuming 1 ...
[P2] Producing 0 ...
[P2] Producing 1 ...
 ------> [C2] Consuming 0 ...
 ------> [C2] Consuming 1 ...
[P3] Producing 0 ...
[P3] Producing 1 ...
 ------> [C3] Consuming 0 ...
 ------> [C3] Consuming 1 ...
[P1] Producing 2 ...
[P1] Producing 3 ...
 ------> [C1] Consuming 2 ...
 ------> [C1] Consuming 3 ...
[P2] Producing 2 ...
[P2] Producing 3 ...
 ------> [C2] Consuming 2 ...
 ------> [C2] Consuming 3 ...
[P3] Producing 2 ...
[P3] Producing 3 ...
 ------> [C1] Consuming 2 ...
[P2] Producing 4 ...
 ------> [C2] Consuming 3 ...
[P3] Producing 4 ...
 ------> [C3] Consuming 4 ...
 ------> [C3] Consuming 4 ...