我不太喜欢调度线程,我有大约4-5个线程,每个线程都会在随机时间将数据添加到一个相同的缓冲区。我如何调度线程,这样就不会有两个或更多线程同时访问缓冲区?我在Windows环境下用C语言编写代码。
提前谢谢。
发布于 2012-01-10 05:06:48
共享缓冲区需要受到保护,以防止不同线程的并发读/写。应该使用同步对象来防止这种情况发生。每当线程想要从共享缓冲区读取或写入时,它都会获取锁,在共享缓冲区上执行操作,并在不再需要该缓冲区时释放锁。
同步对象的一个示例是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);发布于 2012-01-10 05:15:16
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库。使用pthread_mutex_lock获取互斥锁,并使用pthread_mutex_unlock释放它。所有请求相同锁的线程都将被阻塞,直到互斥被释放。这保证了只有一个线程可以访问您的共享数据。
发布于 2012-01-10 05:31:58
您需要实现对ressource (缓冲区)的独占访问。在Windows下,我会使用Mutexes (参见Windows API中的CreateMutex和WaitForSingleObject/WaitForMultipleObjects )。
https://stackoverflow.com/questions/8795035
复制相似问题