2012-01-09 161 views
0

我没有太多的调度线程,我喜欢4-5个线程,他们每个人都会随机添加数据到同一个缓冲区。 我该如何安排线程,以便不会有两个或更多线程同时访问缓冲区? 我在C环境下编码。共享一个缓冲区 - 线程安全

在此先感谢。

+1

这是C或C++,因为你有一个boost的标签? – hmjd 2012-01-09 20:54:19

+0

C,对不起,如果这是错误的标签.... – VisaToHell 2012-01-09 21:06:54

+0

什么样的缓冲区 - 它是如何组织的? – 2012-01-13 21:47:07

回答

1

共享缓冲区需要通过不同线程进行并发读写保护。应该使用同步对象来防止发生这种情况。只要线程想要读取或写入共享缓冲区,它就会获取锁,在共享缓冲区上执行其操作,并在无需占用缓冲区时释放锁。

一个例子同步对象是CriticalSection

static CRITICAL_SECTION shared_buffer_lock; 
static char shared_buffer[10]; 

int main() 
{ 
    InitializeCriticalSection(&shared_buffer_lock); 

    /* Start threads */ 
    ... 

    /* Wait for threads */ 
    ... 

    DeleteCriticalSection(&shared_buffer_lock); 

    return 0; 
} 

/* In thread.. */ 

/* Obtain sole access to 'shared_buffer' */ 
EnterCriticalSection(&shared_buffer_lock); 

/* Use 'shared_buffer' ... */ 

/* Release sole access of 'shared_buffer' */ 
LeaveCriticalSection(&shared_buffer_lock); 
+0

感谢小伙子非常有帮助:) – VisaToHell 2012-01-09 21:27:00

1
pthread_mutex_t   mutex = PTHREAD_MUTEX_INITIALIZER; 
int      sharedData=0; 

void *func(void *parm) 
{ 
    int rc; 
    printf("Thread Entered\n"); 
    pthread_mutex_lock(&mutex); 

    /********** Critical Section *******************/ 
    printf("Start critical section, holding lock\n"); 
    ++sharedData; 
    printf("End critical section, release lock\n"); 

    /********** Critical Section *******************/ 
    pthread_mutex_unlock(&mutex); 


} 

上面的例子显示,你所寻找的,使用并行线程库。使用pthread_mutex_lock获取互斥锁,然后使用pthread_mutex_unlock释放它。所有请求相同锁的线程都将被阻塞,直到释放互斥锁。这保证只有一个线程可以访问您的共享数据。

0

您需要实现对资源(缓冲区)的独占访问。在Windows下,我将使用Mutexes(请参阅Windows API中的CreateMutex和WaitForSingleObject/WaitForMultipleObjects)。