我有一个pthread程序,其中线程函数访问main更新的信息。我使用互斥锁来确保同步,但我仍然在观察内存损坏:
.
此处数据已损坏。我有下面的代码段。我不确定我是否错过了什么。请提供您的建议。
/* Global info*/
struct ThreadParams {
struct ofconn *ofconn;
const struct ofp_header *request;
};
#define NTHREADS 1
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
struct ThreadParams threadParams;
enum ercode
handle_request(struct conn *conn, const struct header *request)
{
int rc;
printf("\n%s in!!",__func__);
threadParams.conn = conn;
threadParams.request = request;
printf("\n\t%s: Request type %d", __func__,threadParams.request->type);
printf("\n\t%s: Unlocking Mutex!!",__func__);
rc = pthread_mutex_unlock(&mutex);
checkResults("pthread_mutex_unlock()\n", rc);
printf("\n\t%s: Completed\n",__func__);
return 0;
}
void *thread_func()
{
int rc;
enum ercode error;
printf("\n%s In!!",__func__);
printf("\n%s: Locking Mutex!!\n",__func__);
rc = pthread_mutex_lock(&mutex);
checkResults("pthread_mutex_lock()\n", rc);
printf("\n%s:Received Lock with Request type %d",
__func__, threadParams.request->type); // data is corrupted here
struct util_request fsr;
error = _decode__request(&fsr, threadParams.request);
if (error) {
return 1;
}
printf("\n\t%s: UnLocking Mutex!!",__func__);
rc = pthread_mutex_unlock(&mutex);
checkResults("pthread_mutex_lock()\n", rc);
return NULL;
}
int main(void)
{
int rc=0, i;
pthread_t threadid[NTHREADS];
printf("\n%s: Locking Mutex!!\n",__func__);
rc = pthread_mutex_lock(&mutex);
checkResults("pthread_mutex_lock()\n", rc);
for(i=0; i<NTHREADS; ++i) {
rc = pthread_create(&threadid[i], NULL, thread_func, NULL);
checkResults("pthread_create()\n", rc);
}
sleep(5);
printf("\nCalling hanlde__request function\n");
handle_request(ofconn, request);
return 0;
}