pthread中的共享对象

时间:2013-06-19 23:20:29

标签: pthreads shared

我想编写一个示例程序,其中16个线程可以访问具有巨大大小(如10gb)的共享对象。我知道我可以使用pthread_mutex_t获取对象的锁定,但是如何使其有效,以便两个或多个线程可以同时修改共享对象的不相交部分?

2 个答案:

答案 0 :(得分:2)

也许你可以创建一个10 pthread_mutex_t的数组,每1gb范围一个,并为你要修改的范围锁定适当的互斥锁?

答案 1 :(得分:1)

使用信号量怎么样?您可以使用共享资源的线程数来初始化信号量。

    /* 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 */
}