【问题标题】:Change C thread parameters while executing the thread在执行线程时更改 C 线程参数
【发布时间】:2019-05-02 22:04:24
【问题描述】:

我需要动态更新线程函数的参数。该函数接收3个参数,并且:

  • 退出标志 (int)
  • 退出标志的互斥体参数
  • 股票市场结构

lib/concurrency_layer.c:

void * operation_executer(void *args){
   pthread_mutex_lock(&marketMutex);

   struct exec_info *execData = args;        //Parsing data from parameters
   stock_market *market = execData->market;  // Create stock market structure
   pthread_mutex_unlock(&marketMutex);

   pthread_mutex_lock(execData->exit_mutex);
   // Waits until exit flag it's 1
   while(*(execData->exit) == 0){           
        pthread_cond_wait(&exitCond, execData->exit_mutex);
   }
   pthread_mutex_unlock(execData->exit_mutex);

   pthread_mutex_lock(&marketMutex);

    struct operation op;
    while(operations_queue_empty(market->stock_operations) == 0){
            dequeue_operation(market->stock_operations, &op);
            process_operation(market, &op);
    }
    pthread_mutex_unlock(&marketMutex);
}

我尝试过使用 pthread 条件,但我不知道在哪里发出信号,因为主函数中的退出标志发生了变化(在不同的文件中):

#include "include/concurrency_layer.h";

int main(){
   exit = 0;
    exec_info info_ex1;
    info_ex1.market = &market_madrid;
    info_ex1.exit = &exit;
    info_ex1.exit_mutex = &exit_mutex;



    pthread_create(&(tid[1]), NULL, &operation_executer, (void*) &info_ex1);

    pthread_mutex_lock(&exit_mutex);
    exit = 1;
    pthread_mutex_unlock(&exit_mutex);

    pthread_join(tid[1],&res);
}

这个想法是函数必须在exit=1时执行。

我可以在 lib/concurrency_layer.h 中添加额外的全局变量、函数、互斥体、条件...,但我不能修改 include/concurrency_layer.h,所以我不能使用函数来激活信号。

【问题讨论】:

  • 条件变量是这项工作的不错选择。我不明白你在使用一个时会遇到什么问题。为什么设置退出标志的代码驻留在哪个源文件中很重要?
  • pthread_cond_wait 将永远等待,因为您在设置 exit 标志后永远不会发出条件信号。设置exit 后,您需要从主线程调用pthread_cond_signal(&exitCond);。此外,无需在主线程中获取互斥锁来设置标志和发出条件信号。
  • 如果在任何地方使用<stdlib.h>,使用全局变量exit 会导致混淆——它与exit() 函数冲突。选择一个不同的非保留名称。
  • @JonathanLeffler exit 这里是局部变量和结构成员的名称。 exit 不是只为全局名称保留的吗?
  • @MaximEgorushkin — 鉴于int main(){ exit = 0;exit 不可能是局部变量。是的,如果它是在main() 中定义的(例如,使用int main(){ int exit = 0;),那么您只会感到困惑。您可以将exit 用作(结构或联合的)成员,但不是特别推荐。但是全局变量是骇人听闻的,如果是局部变量,那就太不明智了。详情请见C11 §7.1.3 Reserved identifiers

标签: c multithreading pthreads


【解决方案1】:

我认为线程将在operation_executer() 中的pthread_cond_wait() 处陷入死锁状态,因为您没有在程序中的任何地方调用pthread_cond_singal()。如果你很幸运并且exit = 1;main() 之前在while(*(execData->exit) == 0) 之前执行,它可能会起作用。

您需要进行以下更改。

  1. 如下所示,在制作exit = 1; 后从main 调用pthread_cond_singal()

    pthread_mutex_lock(&exit_mutex); exit = 1; pthread_cond_singal(&exitCond); pthread_mutex_unlock(&exit_mutex);

  2. 您可以在operation_executer() 中将while(*(execData->exit) == 0) 更改为if(*(execData->exit) == 0),因为您只需检查一次exit 标志。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-12-19
    • 2021-10-03
    • 2014-12-20
    • 2023-03-10
    • 1970-01-01
    • 2016-06-18
    • 1970-01-01
    相关资源
    最近更新 更多