【发布时间】:2016-04-18 11:47:38
【问题描述】:
你好,下面是我的编码sn-p
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
#define TIMEOUT 3
int threadFinished = 0;
pthread_mutex_t g_mutex;
void *threadFunction(void* attr)
{
pthread_mutex_lock(&g_mutex);
char *pData = (char*)attr;
if(pData)
{
printf("data from main thread is : %s\n",pData);
}
sleep(10);
threadFinished = 1;
pthread_mutex_unlock(&g_mutex);
return (void*)"This is thread message !";
}
int main()
{
pthread_t tid;
char *retVal = NULL;
int iTimeOut = TIMEOUT;
int i =0;
pthread_mutex_init(&g_mutex,NULL);
pthread_create(&tid,NULL,threadFunction,"Message from main thread");
//printf("itimeout %d , threadrunning %d\n",iTimeOut,threadRunning);
while(iTimeOut!=0 && !threadFinished)
{
printf("waiting %d\n",++i);
sleep(1);
iTimeOut--;
printf("changing the threadfinish varible\n");
//pthread_mutex_lock(&g_mutex); //statement 1
threadFinished = 1;
//pthread_mutex_unlock(&g_mutex); // statement 2
printf("changed the threadfinish varible\n");
}
if(iTimeOut==0)
{
if(!threadFinished)
{
printf("Timed out so cancelling the thread \n");
pthread_cancel(tid);
}
else
{
printf("thread finished \n");
}
}
else
{
printf("thread finished its job \n");
pthread_join(tid,(void*)&retVal);
}
pthread_mutex_destroy(&g_mutex);
threadFinished = 0;
printf("message from thread is : %s\n",retVal);
return 0;
}
当 statement1 和 statement2 被注释时,我希望子线程在主线程之前首先更改我的 testrunning 变量,但它只有在 statement1 和 statement2 未注释时才能正常工作。
我的问题是为什么在子线程中互斥锁没有锁定我的 testrunning 变量。它允许主线程修改testrunning 变量。
【问题讨论】:
-
锁只锁住自己。您不能锁定变量。这甚至意味着什么?
-
@大卫。我的天啊 !简单直接的回答谢谢。我现在明白了,非常感谢
标签: c linux multithreading pthreads