Each thread, whenever it runs, writes a message to standard output and decrements a counter. When the counter reaches zero, the thread terminates. When both threads have terminated, the scheduler terminates.
This program shows how two threads may run the same code but behave differently, because they have different values for their thread-private data. They issue different messages, and because they are initialized with different values for their counters, they repeat for a different number of times.
The output of the program looks like this:
When it creates each thread, the program dynamically allocates a struct to hold the message and the counter. It passes a pointer to that struct toCheap threads demo #1 Hello from thread A This is coming from thread B Hello from thread A This is coming from thread B Hello from thread A This is coming from thread B Hello from thread A This is coming from thread B Hello from thread A This is coming from thread B This is coming from thread B This is coming from thread B This is coming from thread B
ct_create_thread() so that the thread can
access the struct. The program also installs a destructor for each
thread, so that the dynamically allocated memory is freed when the
thread terminates.
For this simple demo, the use of dynamically allocated memory is perhaps overkill. It would have been simpler to install pointers to statically allocated memory. However the use of dynamically allocated memory is a more general and more flexible approach, especially when you don't know in advance how many threads you will need.