谁能建议如何使用 pthread_mutex_lock 优化下面的应用程序代码?
让我描述一下情况:
我有 2 个线程共享一个全局共享内存变量。该变量shmPtr->status在两个函数中都受到互斥锁的保护。虽然sleep(1/2)task1 函数中有一个“for 循环”,但我无法shmPtr->status在需要时访问 task2 中的,必须等到 task1 函数中的“for 循环”完成。大约需要 50 秒shmPtr->status才能使用 task2 功能。
我想知道为什么 task1 函数没有释放互斥锁,尽管这sleep(1/2)条线。我不想等待shmPtr->status在 task2 函数中处理。请指教。
thr_id1 = pthread_create ( &p_thread1, NULL, (void *)execution_task1, NULL );
thr_id2 = pthread_create ( &p_thread2, NULL, (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