Applying C - Pthreads |
Written by Harry Fairhead | ||||||||
Monday, 25 September 2023 | ||||||||
Page 4 of 4
You can create a thread local in Pthreads using: __thread as a qualifier on any static or global variable. This is a widely supported POSIX standard but there are other ways of doing the job and in particular C11 introduced its own way that works if you are using C11 threading. As an example, let’s try two simple counting threads sharing a global counter variable: #include <stdio.h> #include <stdlib.h> #include <pthread.h> int counter; void * count(void *p) { for (int i = 0; i < 5000; i++) { counter++; } return &counter; } int main(int argc, char** argv) { pthread_t pthread1; int id1 = pthread_create( You can see that the counter variable is global and both threads increment it 5000 times. It might appear that the result of printing the two return values would be 5000 each time. However, as both threads access the variable in an uncontrolled way sometimes things go wrong as both threads access the count variable at the same time - take the same value it contains, increment it and store the same incremented value back. What should have been an increment by two becomes an increment by one. If you run the program you will get results in the 6000 region indicating the simultaneous updates aren't that rare. Now if you change the declaration of count to: __thread int counter; and rerun the program you will see that returnval1 prints 5000 and returnva2 prints 5000 also. Each thread has its own copy of the global count variable and there is no sharing and hence no interaction. Of course the variable is still global and any other function executed on the same thread will have access to its value. A thread local variable is safe to use within a thread but how do we correct the counter program with a shared global so that we always get the right answer - the most obvious answer is use a lock but there is another. Included in chapter but not in this extract:
Summary
Now available as a paperback or ebook from Amazon.Applying C For The IoT With Linux
Also see the companion book: Fundamental C <ASIN:1871962609> <ASIN:1871962617> Related ArticlesRemote C/C++ Development With NetBeans Getting Started With C/C++ On The Micro:bit To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.
Comments
or email your comment to: comments@i-programmer.info |
||||||||
Last Updated ( Tuesday, 26 September 2023 ) |