Skip to content

Eat, Sleep, Spaghetti, repeat. This project is about learning how threads work by precisely timing a group of philosophers on when to pick up forks and eat spaghetti without dying from hunger.

Notifications You must be signed in to change notification settings

ava8kyoko/42-philosophers

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

27 Commits
 
 
 
 
 
 
 
 

Repository files navigation

42-philosophers

Index

  • [Data Race](## Data Race)

Tests

Don't forget to add 10 ms to time_to_die because it can print after the philo's death.
"A message announcing a philosopher died should be displayed no more than 10 ms after the actual death of the philosopher."

./philo 2 110 200 200

./philo 2 410 200 200 > test
cat test | grep -c "1 is eating"

Data Race

C11 introduced support for multiple threads of execution, which affords the possibility of data races. A program contains a data race if an object in it is accessed1 by two different threads, where at least one of the accesses is non-atomic, at least one modifies the object, and program semantics fail to ensure that the two accesses cannot overlap temporally.2 Note well that actual concurrency of the accesses involved is not a condition for a data race; data races cover a broader class of issues arising from (allowed) inconsistencies in different threads' views of memory.

Consider this example:

#include <threads.h>

int a = 0;

int Function( void* ignore )
{
    a = 1;

    return 0;
}

int main( void )
{
    thrd_t id;
    thrd_create( &id , Function , NULL );

    int b = a;

    thrd_join( id , NULL );
}
The main thread calls thrd_create to start a new thread running function Function. The second thread modifies a, and the main thread reads a. Neither of those access is atomic, and the two threads do nothing either individually or jointly to ensure that they do not overlap, so there is a data race.

Among the ways this program could avoid the data race are

the main thread could perform its read of a before starting the other thread;
the main thread could perform its read of a after ensuring via thrd_join that the other has terminated;
the threads could synchronize their accesses via a mutex, each one locking that mutex before accessing a and unlocking it afterward.
As the mutex option demonstrates, avoiding a data race does not require ensuring a specific order of operations, such as the child thread modifying a before the main thread reads it; it is sufficient (for avoiding a data race) to ensure that for a given execution, one access will happen before the other.

Testers

References:

About

Eat, Sleep, Spaghetti, repeat. This project is about learning how threads work by precisely timing a group of philosophers on when to pick up forks and eat spaghetti without dying from hunger.

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published