0

我有一个简单的线程程序,它使用条件变量和 rwlock。我已经盯着它看了好几个小时,尝试了不同的方法。问题是一个或多个线程在一段时间后在 rwlock 处停止,尽管它没有被锁定以进行写入。也许我错过了一些关于这些锁是如何工作的或者它们是如何实现的。

#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <time.h>
#include <math.h>
#include <unistd.h>

//global variables
pthread_mutex_t mutex;
pthread_cond_t cond;
pthread_rwlock_t rwlock;
int counter;
int listLength = 1;

void* worker(void* arg){
   do {
      usleep(200);
      printf("Before rwlock\n");
      pthread_rwlock_rdlock(&rwlock);
      printf("Before mutex\n");
      pthread_mutex_lock(&mutex);
      printf("Afer mutex\n");
      counter++;
      //signal the main
      if (counter == 5 ||
               (listLength < 5 && counter == listLength)){
          printf("Signal main\n");
          pthread_cond_signal(&cond);
          counter = 0;
      }
      pthread_mutex_unlock(&mutex);
      pthread_rwlock_unlock(&rwlock);
   } while(listLength != 0);

   return NULL;
}


int main(int argc, char* argv[]){
    if (argc != 2){
        perror("Invalid number of args");
        exit(1);
    }
    //get arguments
    int workers = atoi(argv[1]);

    //initialize sync vars
    pthread_rwlockattr_t attr;
    pthread_rwlockattr_setkind_np(&attr,
            PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP);
    pthread_mutex_init(&mutex, NULL);
    pthread_cond_init(&cond, NULL);
    pthread_rwlock_init(&rwlock, &attr);
    counter = 0;

    //create threads
    pthread_t threadArray[workers];
    int threadOrder[workers];
    for (int i = 0; i < workers; i++){
        threadOrder[i] = i;
        if (pthread_create(&threadArray[i], NULL,
                    worker, &threadOrder[i]) != 0){
            perror("Cannot create thread");
            exit(1);
        }
    }

    while(listLength != 0) {
        //wait for signal and lock the list
        pthread_mutex_lock(&mutex);
        while (pthread_cond_wait(&cond, &mutex) != 0);
        pthread_rwlock_wrlock(&rwlock);
        printf("In write lock\n");

        pthread_mutex_unlock(&mutex);
        pthread_rwlock_unlock(&rwlock);
        printf("release wrlock\n");
    }

    //join the threads
    for (int i = 0; i < workers; i++){
        if (pthread_join(threadArray[i], NULL) !=0){
            perror("Cannot join thread");
           exit(1);
        }
    }

    //release resources
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    pthread_rwlock_destroy(&rwlock);

    return 0;
}
4

1 回答 1

1

看起来这段代码有几个不一致的地方。

  1. mutex一起使用rwlock这意味着所有这种类型的线程总是被锁定的。如果您删除rwlock代码 - 它不会改变行为。

  2. 我看不到pthread_rwlock_init()电话,假设你在另一个地方打过电话。无论如何要注意你确实调用它并且你不要用同一个rowlock对象调用它两次或更多次。

    这同样适用于pthread_rwlockattr_destroy()

  3. 我看不出 pthread_rwlock_rdlock() 会在没有写锁的情况下阻塞的原因。确保你不要这样做。否则你可以做一个互锁mutex

于 2013-11-10T09:35:21.653 回答