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 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 ...