#Mutex locks and threads- conditional is not being correctly checked.

19 messages · Page 1 of 1 (latest)

proven nicheBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question run !howto ask.

elder hemlock
#
WARNING: ThreadSanitizer: data race (pid=1)
  Read of size 4 at 0x0000004040c0 by thread T2:
    #0 train_func(void*) /app/example.cpp:25 (output.s+0x4012a1)
    #1 <null> <null> (libtsan.so.0+0x333cf)

  Previous write of size 4 at 0x0000004040c0 by thread T1 (mutexes: write M9):
    #0 train_func(void*) /app/example.cpp:55 (output.s+0x401525)
    #1 <null> <null> (libtsan.so.0+0x333cf)

  Location is global 'station_pop' of size 20 at 0x0000004040c0 (output.s+0x0000004040c0)

  Mutex M9 (0x000000404100) created at:
    #0 pthread_mutex_init <null> (libtsan.so.0+0x4d483)
    #1 main /app/example.cpp:126 (output.s+0x401c21)

  Thread T2 (tid=4, running) created by main thread at:
    #0 pthread_create <null> (libtsan.so.0+0x5fdc5)
    #1 main /app/example.cpp:134 (output.s+0x401c8c)

  Thread T1 (tid=3, running) created by main thread at:
    #0 pthread_create <null> (libtsan.so.0+0x5fdc5)
    #1 main /app/example.cpp:129 (output.s+0x401c4d)

SUMMARY: ThreadSanitizer: data race /app/example.cpp:25 in train_func(void*)
#

so basically you have some UB because station_pop[i] != 0 happens at the same time as station_pop[current_station] -= passengers_pickup;

#

it might not be the cause, but it's definitely an issue

#
current_station == 0

and

current_station++;

should also be a data race

#

the execution that you're getting there is only plausible with optimizations enabled, I think

#

but it makes total sense why it happens

#

Train 1 sees

int current_station = 0;

and can safely assume that no other thread was able to modify this, because that would be a data race and thus UB

so

if (current_station == 0) {

is always true

halcyon ingot
#

this is my updated function

#

i only get up to this point:

#

Train 0 ENTERS Station 0
Station 0 has 500 passengers to pick up
Picking up passengers...
Train 0 picked up 100 passengers at Station 0 and now has 100/100 passengers
Station 0 has 400 passengers to pick up
Train 0 LEAVES Station 0

elder hemlock
#

simple variables like counters don't need locks, they just need to be atomic to be modified thread-safely

#

and you can run the program in a debugger to see where each thread gets stuck

proven nicheBOT
#

@halcyon ingot Has your question been resolved? If so, run !solved :)

proven nicheBOT
#

@halcyon ingot

Please Do Not Delete Posts!

Please don't delete forum posts. They can be helpful to refer to later and other members can learn from them. In the future you can use !solved to close a post and mark a post as solved.

halcyon ingot
#

!solved