Home Upgrade Search Memberlist Extras Hacker Tools Award Goals Help Wiki Contact

C 

Is there any way to safely use a mutex in a detached thread?

This code has a fairly obvious race condition. Since the stack of detached threads is not unwound, objects' destructors may well not be called.

About 15-20% of the time I run this code in debug mode, it throws an error saying that a mutex was destroyed while in use. Fairly obviously.

This is what the error looks like: (Click to View)

PHP Code

<?php 
#include <thread>
#include <memory>
#include <iostream>
#include <numeric>
#include <mutex>

auto mu = std::make_shared<std::mutex>();

struct Test {
    
int nums[10];
    
int sum(void) const {
        
int s = 0;
        for (
int i = 0; i < 10; ++i)
            
s += nums[i];
        return 
s;
    }
};

void bar(std::shared_ptr<Test> test) {
    
std::lock_guard<std::mutex> lock(*mu);
    
std::cout << test->sum() << std::endl;
}

void foo(int i) {
    for (
int ctr = 0; ctr < i; ++ctr) {
        
auto ptr = std::make_shared<Test>(Test());
        
// perhaps alter ptr->nums...
        
auto t = std::make_shared<std::thread>(std::bind(&bar, ptr));
        
t->detach();
    }
}

int main(int argc, char **argv) {
    
std::thread t(std::bind(&foo, 10));
    
t.join();
    return 
0;
} 

Now, in a project I'm working on, I have an async event loop that needs to send data to a user-provided callback. Since the event loop itself cannot be blocked, I need to spawn the callback in a new thread and detach it so I can continue the event loop, and simply assume the callback does not viciously violate thread safety. It is similar to the setup I have: a thread other than the main thread runs an event loop. Functions called by the event loop will spawn a thread for the callback.

Assuming the user uses a mutex, it seems there is no way to guarantee safety here...

Any tips? Do I have some major design flaws? Help is appreciated.
SRPP Discord Server

I am a professional network/cloud security architect.
My Old Tutorials
Hi,

Is it really necessary to use a pointer on the mutex ?

Also : Detached threads are not joinable.
(Sep 11, 2016 07:26 PM)sqsgkrlhdwg Wrote:  Hi,

Is it really necessary to use a pointer on the mutex ?

Also : Detached threads are not joinable.

Well I had it set up differently at first, fyi, but no, not necessarily.
SRPP Discord Server

I am a professional network/cloud security architect.
My Old Tutorials


Possibly Related Threads...
Thread / Author Replies Views Last Post
[.NET] by Drizzy‎‎May 29, 2026 02:17 AM 61 4,759 May 29, 2026 02:17 AM
Last Post: dvs1626
[.NET] by FooterAug 17, 2019 12:02 PM 5 230 Aug 17, 2019 12:02 PM
Last Post: Fhack
[C#] by Iera NamhorunFeb 14, 2019 11:39 PM 10 420 Feb 14, 2019 11:39 PM
Last Post: Iera Namhorun