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:
The piece of code above defines a new datatype, called struct Example
{
int my_int;
char my_char;
int * my_int_pointer;
};
struct Example.
You can now create variables of this type using
and access fields of the structure using the dot notation:
struct Example name_of_variable;
In case of pointer variables of this type
name_of_variable.my_int = 5;
name_of_variable.my_char = 'a';
name_of_variable.my_int_pointer = &(name_of_variable.my_int);
you can access fields of the structure using the arrow operator:
struct Example * pointer_variable;
pointer_variable->my_int = 5;
pointer_variable->my_char = 'a';
pointer_variable->my_int_pointer = &(pointer_variable->my_int);
hellostruct-arr.c
pthreads program that illustrates a safe way to
pass multiple arguments to threads during thread creation, using arrays of structures. hellostruct-ptr.c
pthreads program that illustrates a safe way to
pass multiple arguments to threads during thread creation, using pointers to structures. 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 ...