2013-06-19 134 views
0

我想編寫一個示例程序,其中16個線程可以訪問像10gb這樣巨大大小的共享對象。我知道我可以使用pthread_mutex_t來獲取對象的鎖定,但是如何使其有效,以便兩個或多個線程可以同時修改共享對象的不相交部分?pthread中的共享對象

回答

2

也許你可以創建一個10個pthread_mutex_t的數組,每個1gb範圍一個,並且鎖定你將要修改的範圍的適當的互斥鎖?

+0

謝謝。你知道任何例子,因爲我不知道如何管理範圍! – Sara

+0

在不瞭解應用程序的情況下很難舉一個例子。你對線程如何訪問共享對象的各個部分有什麼想法嗎? – faffaffaff

+0

他們只是寫一些信息。 – Sara

1

怎麼樣使用sempahore。您可以使用共享資源的線程數初始化信號量。

/* Includes */ 
#include <unistd.h>  /* Symbolic Constants */ 
#include <sys/types.h> /* Primitive System Data Types */ 
#include <errno.h>  /* Errors */ 
#include <stdio.h>  /* Input/Output */ 
#include <stdlib.h>  /* General Utilities */ 
#include <pthread.h> /* POSIX Threads */ 
#include <string.h>  /* String handling */ 
#include <semaphore.h> /* Semaphore */ 

void semhandler (void *ptr); 

sem_t mutex; 
int cntr=0; /* shared variable */ 

int main() 
{ 
    int arg[2]; 
    pthread_t thread1; 
    pthread_t thread2; 

    arg[0] = 0; 
    arg[1] = 1; 

    /* initialize mutex to 2 to share resource with two threads*/ 
    /* Seconds Argumnet "0" makes the semaphore local to the process */ 
    sem_init(&mutex, 0, 2); 

    pthread_create (&thread1, NULL, (void *) &semhandler, (void *) &arg[0]); 
    pthread_create (&thread2, NULL, (void *) &semhandler, (void *) &arg[1]); 

    pthread_join(thread1, NULL); 
    pthread_join(thread2, NULL); 

    sem_destroy(&mutex); 

    exit(0); 
} /* main() */ 

void semhandler (void *ptr) 
{ 
    int x; 
    x = *((int *) ptr); 
    printf("Thrd %d: Waiting to enter critical region...\n", x); 
    sem_wait(&mutex);  /* down semaphore */ 
    if(x == 1) 
     cntr++; 

    /* START CRITICAL REGION */ 
    printf("Thrd %d: Now in critical region...\n", x); 
    printf("Thrd %d: New Counter Value: %d\n", x, cntr); 
    printf("Thrd %d: Exiting critical region...\n", x); 
    /* END CRITICAL REGION */ 
    sem_post(&mutex);  /* up semaphore */ 

    pthread_exit(0); /* exit thread */ 
} 
+0

謝謝,但巨大的共享對象呢? – Sara

+0

如何在對象內添加一個「互斥體」變量?在使用該對象之前先取出該互斥體,然後在完成後釋放它 –