gpt4 book ai didi

c - 变量失去值(value)

转载 作者:行者123 更新时间:2023-11-30 15:47:49 25 4
gpt4 key购买 nike

启动一个分离线程后,该线程会休眠一段时间。在 sleep 时间结束时,变量发生了变化。但变量只改变线程中的值。线程退出后,更改不再存在。

该代码在 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;
}

最佳答案

您没有memory synchronization在“sleepTask”线程和主线程之间。

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

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

关于c - 变量失去值(value),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17199341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com