Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/155.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ pthreads-强制线程运行_C++_C_Multithreading_Pthreads_Signals - Fatal编程技术网

C++ pthreads-强制线程运行

C++ pthreads-强制线程运行,c++,c,multithreading,pthreads,signals,C++,C,Multithreading,Pthreads,Signals,我有一个从主线程调用的函数: void create_thread() { pthread_t bg_thread; pthread_create(&bg_thread, NULL, run_in_background, NULL); //wait here pthread_mutex_lock(&MAIN_MUTEX); pthread_cond_wait(&wakeUpMainThread, &MAIN_MUT

我有一个从主线程调用的函数:

void create_thread() {    
    pthread_t bg_thread;
    pthread_create(&bg_thread, NULL, run_in_background, NULL);

    //wait here
    pthread_mutex_lock(&MAIN_MUTEX);
    pthread_cond_wait(&wakeUpMainThread, &MAIN_MUTEX);
    pthread_mutex_unlock(&MAIN_MUTEX);

    pthread_cond_signal(wakeUpBgThread);
}
以下是在后台线程中运行的函数的简短版本:

void* run_in_background(void* v) {                   
    pthread_mutex_t mutex;
    pthread_cond_t  cond;
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);

    //NOTE: wakeUpBgThread == cond
    save_condition_and_mutex(&cond, &mutex);

    pthread_mutex_lock(&mutex);
    {
        pthread_cond_signal(&wakeUpMainThread);

        while( run_condition ) {
            pthread_cond_wait(&cond, &mutex);

            do_smth();
        }
    }
    pthread_mutex_unlock(&mutex);

    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);

    pthread_exit(NULL);
}
因此,目标是:

1. Create a thread in the main one.
2. Make the main thread sleep until the signal from that thread.
3. Make the background thread sleep until the signal from the main thread.
4. Invoke the background thread from the main one.
问题是:有时在

 pthread_cond_signal(&wakeUpMainThread);
调度器立即切换到主线程,并为后台线程发出唤醒信号。在这个调度程序切换回后台线程并开始等待已经触发的信号之后,它将永远休眠

问题:有没有办法强制后台线程执行代码,直到

pthread_cond_wait(&cond, &mutex);

听起来你最好的选择是使用条件。有一个互斥和一个条件。Main初始化两者,获取互斥锁,创建线程,然后根据条件进入睡眠状态。Child抓取锁(在main等待条件后)执行工作(或者执行工作然后抓取锁),然后发出条件信号(您可以决定是在信号之前还是之后释放锁——重要的一点是您抓取了锁)。然后,Main唤醒并继续处理


pthread_cond_wait()和friends就是你所看到的。

你在
创建线程中对
pthread_mutex_lock
的调用需要在之前而不是之后进行。否则,您将面临竞争条件。

是否使用信号量?信号量信号没有丢失-它们只是增加计数&因此后台线程将在信号量发出后再次运行,即使它实际上还没有开始等待它

Rgds,
Martin

在主线程上发送信号之前,不会锁定互斥锁。如果您想要可预测的行为-您应该在等待调用和信号调用之前锁定相同的互斥体。

我应该在之前锁定该互斥体,这是正确的,但我认为这不是真正的问题,因为主互斥体仅在创建新线程时使用,而不在其他任何地方使用,因此它不会影响后台线程的执行。您需要要锁定同一个互斥锁,请在调用“pthread_cond_signal(&wakeUpMainThread);”之前,先锁定主互斥锁。谢谢已经发现了真正的问题。我没有在这里发布的是类中的死锁部分,这并没有改变您发布的代码也有竞争条件的事实。