0

我的问题是我有这段代码:

#include<stdio.h>
#include<semaphore.h>
#include<pthread.h>
    int number;
   pthread_mutex_t mutex[number];
   pthread_t threads[number];


void *dosomething(void *num)
{
   int *i=num;
   pthread_mutex_lock(&mutex[i]);
    //dosomething
   pthread_mutex_unlock(&mutex[i]);
}


int main(int argc, char *argv[]) //<-- main
{

    printf("How many threads do you want?");
     scanf("%d",&number);

     int rc,t;
   for(t=1;t<number;t++){
     pthread_mutex_init(&mutex[t],NULL);
     printf("In main: creating thread %d \n", t);
     rc = pthread_create(&threads[t], NULL, philospher,(void *)t);
            }

     if (rc){
       printf("ERROR; return code from pthread_create() is %d\n",rc);

      exit(0);
            }


   pthread_exit(NULL);
}

当我尝试编译它时,它说:在文件范围内可变地修改了“互斥锁”/在文件范围内可变地修改了“线程”。我只希望它创建许多用户将定义的互斥锁和线程,并且可以从所有创建的线程中使用。

4

1 回答 1

0

这是部分答案。请注意,您发布的代码中还有其他错误(例如使用指针作为索引),并且以下代码仅具有最小可能的错误处理。我会让你理清这些细节。

// ...

int number;
pthread_mutex_t* mutex;  // declare as pointers instead of arrays
pthread_t* threads;      //    so they can be dynamically sized

void alloc_thread_info(int number)
{
    int i;

    // allocate the arrays with the requested size

    mutex = calloc( number, sizeof(*mutex));
    threads = calloc(number, sizeof(*threads));

    if (!mutex || !threads) {
        abort();
    }

    for (i = 0; i < number; ++i) {
        pthread_mutex_init( &mutex[i]);
    }

    return;    
}
于 2013-01-03T22:14:08.240 回答