简体   繁体   中英

How to create a race condition in C++

I want to test some Object's function for thread safety in a race condition. In order to test this I would like to call a function simultaneously from two (or more) different threads. How can I write code that guarantee that the function calls will occur at the same time or at least close enough that it will have the desired effect?

The best you can do is hammer heavily at the code and check all the little signs you may get of an issue. If there's a race-condition, you should be able to write code that will eventually trigger it. Consider:

#include <thread>
#include <assert.h>

int x = 0;

void foo()
{
    while (true)
    {
        x = x + 1;
        x = x - 1;
        assert(x == 0);
    }
}

int main()
{
    std::thread t(foo);
    std::thread t2(foo);

    t.join();
    t2.join();
}

Everywhere I test it, it asserts pretty quickly. I could then add critical sections until the assert is gone.

But in fact, there's no guarantee that it ever will assert. But I've used this technique repeatedly on large-scale production code. You may just need to hammer at your code for a long while, to be sure.

Have a struct having a field of array of integers of zero, probably 300-500 kB long. Then from two threads, copy two other structs (one having 1s another having 2s) to it, just before some atomic memory issuing barriers(to be sure undefined behavior area has finished, from main thread by checking atomic variable's value).

This should have a high chance of undefined behavior and maybe you could see mixed 1s, 2s (and even 0s?) in it to know it happened.

But when you delete all control stuff such as atomics, then new shape can be also another undefined behavior and behave different.

A great way to do this is by inserting well-timed sleep calls. You can use this, for example, to force combinations of events in an order you want to test (Thread 1 does something, then Thread 2 does something, then Thread 1 does something else). A downside is that you have to have an idea of where to put the sleep calls. After doing this for a little bit you should start to get a feel it, but some good intuition helps in the beginning.

You may be able to conditionally call sleep or hit a breakpoint from a specific thread if you can get a handle to the thread id.

Also, I'm pretty sure that Visual Studio and (I think) GDB allow you to freeze some threads and/or run specific ones.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM