变量的价值丢失

时间:2013-06-19 19:08:42

标签: c multithreading pthreads

启动分离线程后,线程会进入休眠状态一段时间。在睡眠时间结束时,变量已更改。但是变量只会改变线程中的值。退出线程后,更改不再存在。

该代码在Lam / MPI 7.4下运行。如果这与正常的gcc不同,现在不要。

typedef struct theadSleep {
    struct task *task;
    int sleeptime;
    int result;
} ThreadSleep;

void sleepTask(void *dummy) {
    static volatile ThreadSleep *tS;
    tS = (ThreadSleep*) dummy;
    time_t t1;
    t1 = time(NULL );
    int t1int = (int) t1;
    t1int = t1int + tS->sleeptime;
    while (t1int >= (int) time(NULL )) {
        sleep(1);
    }
    tS->task->result = tS->result;
    pthread_exit(NULL );
}


// Function to start the thread
pthread_attr_t attrSleep; /* Attribut für Posix Thread */
pthread_t sleepT; /* Posix Thread */
static volatile ThreadSleep ts1;
ts1.result = 0;
ts1.sleeptime = 0;
ts1.result = resultRecieved[0];
ts1.sleeptime = resultRecieved[1];
ts1.task = tmpTask;
pthread_attr_init(&attrSleep);
pthread_attr_setdetachstate(&attrSleep, PTHREAD_CREATE_DETACHED);
if (pthread_create(&sleepT, &attrSleep, &sleepTask, (void*) &ts1)   == -1) {
  fprintf(stderr, "Fehler bei Starten des Sleep Threads Task %i Kind %i.\n",
  tmpTask->taskindex, tmpTask->taskkind);
}

        }

此处标记tS->task->result = tS->result;无效!

示例,但没有错误。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <pthread.h>
#include <unistd.h>

typedef struct task {
        int result;
        int sleeptime;
} Task;

typedef struct theadSleep {
        struct task *task;
        int sleeptime;
        int result;
} ThreadSleep;


void sleepTask(void *dummy) {
    ThreadSleep *tS;
    tS = (ThreadSleep*) dummy;
    time_t t1;

    t1 = time(NULL );
    int t1int = (int) t1;
    t1int = t1int + tS->sleeptime;
    while (t1int >= (int) time(NULL )) {
        sleep(1);
    }
    tS->task->result = tS->result;
    printf("Detach Thread is ready.\n");
    pthread_exit(NULL );
}

int main (){
  Task *newtask = malloc(sizeof(Task));
  newtask->result = 0;
  newtask->sleeptime = 3;

  pthread_attr_t attrSleep; /* Attribut für Posix Thread */
  pthread_t sleepT; /* Posix Thread */
  ThreadSleep ts1;
  ts1.result = 14;
  ts1.sleeptime = newtask->sleeptime;
  ts1.task = newtask;

  pthread_attr_init(&attrSleep);
  pthread_attr_setdetachstate(&attrSleep, PTHREAD_CREATE_DETACHED);
  if (pthread_create(&sleepT, &attrSleep, &sleepTask, (void*) &ts1)
                                        == -1) {
    fprintf(stderr, "Fehler bei Starten des Sleep Threads.\n");
  }
  sleep (5);

  printf("Task result: %i \n",newtask->result);

return 0;
}

2 个答案:

答案 0 :(得分:1)

“sleepTask”线程与主线程之间没有memory synchronization

因此,sleepTask线程可以更新某些内存区域(如tS->task->result),但主线程保证看到此更新。 (最终会,但最终可能会在并发编程中花费很长时间。)

受Mutex保护的访问可以解决这个问题,就像主线程加入工作线程然后检查有问题的内存一样。

答案 1 :(得分:0)

您遗失memcpy(tS, dummy, sizeof(ThreadSleep));
另外,请删除tS = (ThreadSleep*) dummy;
如果您只想在本地进行更改,则适用。否则,忘记memcpy和malloc。在这种情况下,只需将'dummy'转换为ThreadSleep *即可。如果您离开它并且如果您想避免内存泄漏,请添加free();