Pthreads:内存被破坏了

时间:2017-05-09 05:03:30

标签: c multithreading

我有一个pthread程序,其中线程函数访问main更新的信息。我使用互斥锁来确保同步,但我仍然在观察内存损坏:

  1. 主线程获取锁定并应更新全局数据(通过打印调试确保数据正确更新)。发布锁定
  2. 线程将获取锁并访问全局数据.此处数据已损坏。
  3. 我有下面的代码段。我不确定我是否错过了什么。请提供您的建议。

    /* 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;
    }
    

0 个答案:

没有答案