我有一个简单的线程程序,它使用一个条件变量和一个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;
}

最佳答案

看来这段代码有几个不一致之处。
您将mutexrwlock一起使用,这意味着这类线程始终处于锁定状态。如果删除rwlock代码-它不会改变行为。
我看不到pthread_rwlock_init()调用,假设您在另一个地方调用了它。无论如何,请注意,您确实调用了它,但对于同一个rowlock对象,您不会调用它两次或多次。
这同样适用于pthread_rwlockattr_destroy()
我看不出pthread_rwlock_rdlock()在没有写锁的情况下阻塞的原因。千万别这么做。或者你可以对你的mutex

10-07 20:10