【问题标题】:Blocking a thread until some piece of code finishes execution in C [closed]阻塞线程直到某些代码在C中完成执行[关闭]
【发布时间】:2015-05-22 10:53:13
【问题描述】:

在我的 C 程序中,我有 2 个线程,并且两个线程都是从一开始就启动的。我有一个全局变量(一些句柄),并且在 Thread1 函数中进行了修改。 Thread2 函数也使用该全局变量。我想确保 Thread2 函数应该在 Thread1 完成更新变量后使用该变量。

我想在thread1更新全局变量的值时阻塞thread2。

如何实现上述逻辑?

【问题讨论】:

  • 看看使用事件和WaitForSingleObject
  • 古尔格是你的朋友。我将从以下关键字开始:“mutex”(多平台)或“Critical section”(Windows)

标签: c windows multithreading


【解决方案1】:

如果您使用pthread 库,您可以使用互斥锁来阻止其他线程对变量的访问,直到您释放它为止。

你可能想看看这个StackOverflow post 或者这个example

顺便说一下,一些代码会更好地识别你正在尝试做什么。

【讨论】:

  • 请注意,示例代码的线程 2 通过 get_count() 处理全局变量的副本。这最大限度地减少了线程 1 和 2 在互斥体下运行的代码量。
【解决方案2】:

如果此处的目标是让线程 1 和线程 2 并行但同步运行,则使用类似于以下使用信号量的示例(windows 示例):

int count;
    /* thread 1 */
    for(count = 0; count < 20; count++){
        /* allow thread 2 to use count */
        ReleaseSemaphore(semaphore2, 1, NULL);
        /* ... use count here */
        /* wait before count++ */
        WaitForSingleObject(semaphore1, INFINITE);
    }

    /* thread 2 */
int done = 0;
    while(!done){
        /* wait for count to be updated */
        WaitForSingleObject(semaphore2, INFINITE);
        /* ... use count here */
        done = count < 19 ? 0 : 1;
        /* allow thread 1 to update count */
        ReleaseSemaphore(semaphore1, 1, NULL);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 1970-01-01
    • 1970-01-01
    • 2015-01-08
    • 1970-01-01
    相关资源
    最近更新 更多