线程同步,并使用Pthread定义原子块[关闭]。

问题描述 投票:0回答:1

我在使用Pthread编程时遇到了一些问题。

有两个线程(Reader,Main)和共享资源。fd.fd 可以通过以下方式访问 阻挡方式 借用 read_blocking()write_blocking()

我的目的是在主线程中随时写数据,而Reader线程则可以自由运行。我使用Pthread组件(Semaphore,Mutex锁等)来实现,但遇到了同步问题。僵局.

以下是这种情况的简化代码。

Reader线程(自由运行)。

// Read data from `fd`
// (Separated thread other than main thread)
void ReaderThread() {
    while ( 1 ) {

        // [A]

        wait_write_complete(g_lock);

        // [!] "main thread" should NOT cut into here

        read_blocking(fd);  // [B]

    }
}

Writer函数(从主线程调用):

// Write data to `fd`
// Called from "main thread"
void WriteData() {
    lock(g_lock);

    // At this point, the ReaderThread() shoule be @ [A] or [B]

    cancel_read();  // force terminate read_blocking()
    write_blocking(fd);

    unlock(g_lock);
}

[关键点]

  • read_blocking()write_blocking() 趁人之危
  • read_blocking() 可以通过调用 cancel_read()

[要求]

  • 不用忙着等待
  • 没有 sleep()
  • WriteData() 优先于 ReaderThread()(read_blocking() 每当调用WriteData()时都应取消)

  1. 如何预防 WriteData() 间歇 wait_write_complete(g_lock)read_blocking(fd)(标明位置) [!]) ?

    • wait_write_complete(g_lock)read_blocking(fd) 应是原子块
  2. 什么类型的锁定机构适合于 g_lock(Semaphore, Mutex lock, Barrier, Conditional wait, or any other?)

  3. 示例代码将非常非常有帮助! :)

c multithreading synchronization pthreads
1个回答
0
投票

我倾向于同意@EOF的观点,你描述的通信模式似乎过于复杂。 然而,就目前的问题来看,一个 MUT价值 EXclusion锁是一种天然的同步机制,用于排除一个线程在不同线程执行的两个或多个动作之间采取动作。 这大概意味着,为了达到你的目的。wait_write_complete() 必锁 g_lock 在它回来之前,和 read_blocking() 必须在功能进入后尽快解锁。

需要注意的是,你需要非常小心,避免简单地将竞赛条件移入到 read_blocking(). 如何避免这种情况,取决于你打算使用什么机制来中断该函数的执行。

此外,我猜想你会需要一个共享标志来指示写是否待定,读是否可以读(所有的访问都由同一个mutex保护),以及一个条件变量来暂停读的执行,直到写完成。 使用这些。wait_write_complete() 然后可能会是这样的。

int wait_write_complete(pthread_mutex_t *g_lock) {
    int result = pthread_mutex_lock(g_lock);

    while (!result && !may_read) {
        result = pthread_cond_wait(&read_write_cv, &g_lock);
    }

    // Note: if this function returns a failure code then the state of the mutex is unknown 
    return result;
}

作者线程负责操纵 may_read 适当地,在mutex的保护下,并在(重新)启用读数时向条件变量发出信号。

© www.soinside.com 2019 - 2024. All rights reserved.