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 a solution to the multiple producers-consumers problem. Modify this solution so that the sequence of items produced by each producer starts with a different item (letter), denoted start_item in the code. The main thread must compute the value of start_item and pass to each producer thread two pieces of information (in a structure): (i) producer id, and (ii) producer start_item.

Sample output:

[P1] Producing U ...
[P1] Producing V ...
 ------> [C1] Consuming U ...
 ------> [C1] Consuming V ...
[P2] Producing U ...
[P2] Producing V ...
 ------> [C2] Consuming U ...
 ------> [C2] Consuming V ...
[P3] Producing Z ...
[P3] Producing A ...
 ------> [C3] Consuming Z ...
 ------> [C3] Consuming A ...
[P1] Producing W ...
[P1] Producing X ...
 ------> [C1] Consuming W ...
 ------> [C1] Consuming X ...
[P2] Producing W ...
[P2] Producing X ...
 ------> [C2] Consuming W ...
 ------> [C2] Consuming X ...
[P3] Producing B ...
[P3] Producing C ...
 ------> [C1] Consuming B ...
[P2] Producing Y ...
 ------> [C2] Consuming C ...
[P3] Producing D ...
 ------> [C3] Consuming Y ...
 ------> [C3] Consuming D ...
[P1] Producing Y ...
 ------> [C3] Consuming Y ...
[P2] Producing Z ...
 ------> [C2] Consuming Z ...
[P3] Producing E ...
 ------> [C1] Consuming E ...
[P1] Producing Z ...
 ------> [C3] Consuming Z ...