互斥

2013-01-03 126 views
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); 
} 

當我嘗試編譯它,它說: 可變修改的文件範圍「互斥」/ 各種變型文件範圍內的'線程'。 我希望它能夠創建大量用戶定義的互斥鎖和線程,並可從創建的所有線程中使用。

回答

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;  
} 
+0

感謝您reply.I也放在線程一個printf說「你好進出口數量%d線」,但似乎有時當我的線程中創建例如5個線程中的printf有時打印少比5還是有時沒有hellos。 – Izanagi