【问题标题】:Can I make sure that a certain thread always works last, without semaphores?我可以确保某个线程总是最后工作,没有信号量吗?
【发布时间】:2014-10-11 02:58:47
【问题描述】:

所以我有两个线程。一个做数学,另一个显示数学结果。有时,结果线程首先运行并显示 0 而不是有效结果。我怎样才能防止这种情况发生?

void *math  (void *arg);
void *result(void *arg);

int a;

int main(int argc, char *argv[]) {
    pthread_t mathT;
    pthread_t resultT;

    pthread_create(&mathT, NULL, math, NULL);
    pthread_create(&resultT, NULL, result, NULL);

    pthread_join(mathT, NULL);
    pthread_join(resultT, NULL);

    return 0;
}

void *math(void *arg) {
    a = 9 + 9;
    return NULL;
}

void *result(void *arg) {
    printf("%d", a);
    return NULL;
}

【问题讨论】:

  • 那么有两个线程有​​什么意义呢?只需一个线程串行调用这两个函数。
  • 这不是重点。当然,我可以连续执行此操作,但不行,我必须使用单独的线程。
  • pthread_join(mathT)放在pthread_create(resultT)前面。
  • 尝试在math(void*) 中创建结果线程?它可以确保结果线程遵循数学线程。

标签: c multithreading posix mutex


【解决方案1】:

pthread_cond_wait() 阻塞当前线程,然后使用 pthread_cond_signal() 或 pthread_cond_broadcast() 唤醒它

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-28
    相关资源
    最近更新 更多