有人可以建议使用pthread_mutex_lock优化以下应用程序代码吗?
让我描述一下情况:
我有2个线程共享一个全局共享内存变量。这两个函数中的变量shmPtr->status
受互斥锁保护。尽管task1函数的“ for循环”内部有一个sleep(1/2)
,但是当需要时我无法访问task2中的shmPtr->status
,而不得不等到task1中的“ for循环”完成功能。 shmPtr->status
大约需要50秒才能用于task2函数。
我想知道为什么尽管有sleep(1/2)
行,task1函数仍未释放互斥锁。我不想等待在task2函数中处理shmPtr->status
。请指教。
thr_id1 = pthread_create ( &p_thread1,NULL,(void *)execution_task1,NULL );
thr_id2 = pthread_create ( &p_thread2,(void *)execution_task2,NULL );
void execution_task1()
{
for(int i = 0;i < 100;i++)
{
//100 lines of application code running here
pthread_mutex_lock(&lock);
shmPtr->status = 1; //shared memory variable
pthread_mutex_unlock(&lock);
sleep(1/2);
}
}
void execution_task2()
{
//100 lines of application code running here
pthread_mutex_lock(&lock);
shmPtr->status = 0; //shared memory variable
pthread_mutex_unlock(&lock);
sleep(1/2);
}
关于, NK