Operating Systems CMPSC 473
Concurrency: Threads, Data Races & Race Conditions, Mutual Exclusion
April 06, 2021 – Lecture 21 Instructor: Bhuvan Urgaonkar
Thread join
Thread join
• Argument #1: the thread whose termination we want to wait for
• Argument#2:ifretvalisnotNULL,copiestheexitstatusof the target thread (argument to pthread_exit) into the location pointed to by retval
• Return value: 0 on success else error number
Thread self identification
Sample program
• https://man7.org/linux/man- pages/man3/pthread_create.3.html#EXAMPLES
• In lecture: a simplified version of the above (will put code on canvas)
Others to explore on your own
• pthread_attr_init
• pthread_attr_setstack, pthread_attr_getstack • pthread_cancel
Why were some updates “lost?”
• To appreciate this, we need to remember that:
• A C statement such as counter = counter + 1 may compile to multiple
instructions
• An interrupt may arrive any time => no guarantee that the instructions comprising a C statement will execute ”together”
Why were some updates “lost?”
• To appreciate this, we need to remember that:
• A C statement such as counter = counter + 1 may compile to multiple
instructions
• An interrupt may arrive any time => no guarantee that the instructions comprising a C statement will execute ”together”
Why were some updates “lost?”
Why were some updates “lost?”
Why were some updates “lost?”
Why were some updates “lost?”
Data races and race conditions
• A data race: two memory accesses in a program where both:
• target the same virtual address
• are performed concurrently by two threads
• are not reads
• are not synchronization operations
• “race” because the outcome may depend on what interleaving occurs
• e.g., depending on the scheduler, interrupts, etc.
• Aracecondition:aflawthatoccurswhenthetimingororderingof
events affects a program’s correctness • Data races may cause race conditions
Data races and race conditions
Q: can there be a race condition without a data race?
ACK: next 4 examples are from https://blog.regehr.org/archives/490
Data race – yes
Race condition – yes
Data race – no
Race condition – yes
Data race – no
Race condition – no
Data race – yes Race condition – no