【问题标题】:problem with posix threads c++posix线程c ++的问题
【发布时间】:2011-02-08 14:10:44
【问题描述】:

如果我有 2 个线程 Thread1 和 Thread2,但是 Thread2 将使用一些在 Thread1 完成时处理的数据。有没有办法让 Thread2 等待 Thread1 完成然后获取数据?

【问题讨论】:

    标签: multithreading synchronization pthreads


    【解决方案1】:

    如果您需要来自 thread1 的数据,而不仅仅是简单的锁定来防止并发访问,那么您应该使用信号量:

       #include <semaphore.h>
    
       int sem_init(sem_t *sem, int pshared, unsigned int value);
    
       int sem_post(sem_t *sem);
    
       int sem_wait(sem_t *sem);
    
       int sem_trywait(sem_t *sem);
    
       int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
    
       int sem_destroy(sem_t *sem);
    

    主程序在启动线程之前运行 sem_init。线程 1 运行 sem_post 以表明它已完成。线程 2 使用 sem_wait 来确保线程 1 在启动之前完成。

    【讨论】:

      【解决方案2】:

      一种方法是使用条件变量: 例如:

      pthread_mutex_t mx; 
      pthead_cond_t cond; 
      
      void first_f(void *) { 
      ...
          pthread_mutex_lock(&mx) 
      
      // do something in first function
      // the second function is waiting
      
          pthread_cond_signal(&cond); 
          pthread_mutex_unlock(&mx); 
        } 
        return NULL; 
      } 
      
      void second_f(void *) { 
      ...
          pthread_mutex_lock(&mx)    
          pthread_cond_wait(&cond, &mx); 
      
      // waiting for first function until we catch a signal
      
          pthread_mutex_unlock(&mx); 
        } 
        return NULL; 
      } 
      

      第二种方法是使用两个信号量。第一个 sem 设置为 1,第二个设置为零。当第一个函数完成时,它将第一个 sem 设置为 0,将第二个 sem 设置为 1。第二个函数等待直到第二个信号量被第一个函数设置为 1 并开始工作。

      【讨论】:

      • 感谢您的解释,我想我会使用信号量
      • 我同意你的看法。信号量更灵活。
      【解决方案3】:

      它被称为互斥体。 pthreads 调用 pthread_mutex,您应该在文档中找到它们。

      【讨论】:

        【解决方案4】:

        是的,您可以使用互斥锁来“保护”相关数据:

        int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr);
        int pthread_mutex_lock(pthread_mutex_t *mutex);
        int pthread_mutex_trylock(pthread_mutex_t *mutex);
        int pthread_mutex_timedlock(pthread_mutex_t *mutex, const struct timespec *abs_timeout);
        int pthread_mutex_unlock(pthread_mutex_t *mutex);
        int pthread_mutex_destroy(pthread_mutex_t *mutex);
        

        【讨论】:

        • 我知道互斥锁,但我不知道如何在我的情况下使用它们。Thread1 处理具有 2 个静态数据的类,thread2 需要使用这些静态数据 Class::data1, Class::data2 ,我知道只有在同一个线程中访问相同的数据时才使用互斥锁。我的 Thread2 使用来自 thread1 的 get 函数获取数据
        猜你喜欢
        • 1970-01-01
        • 2010-12-13
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-10-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多