gpt4 book ai didi

c线程并发和内存混合

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

我有一个 C 语言的多线程程序。只有 1 个线程函数 (thread_read_file),它将从结构中将文件内容读入变量。该函数有一个自动变量thiscontent,其中应使用fread存储文件的内容。

主程序正在执行4个线程,定期读取4个不同的文件,并将内容更新到内存中。

无论我尝试什么,一段时间后我都会得到结果,然后会出现一些垃圾。我尝试在阅读后强制添加“\0”,但是不行,它无论如何都会显示垃圾。

这是代码:

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

#define WAIT_TIME 2

/* change_it:
* 8: picture for texture 0 finished to load into ram, needs to be set to 2 afterwards
* 7: picture for texture 0 loading
* 6: picture for texture 1 finished to load into ram, needs to be set to 2 afterwards
* 5: picture for texture 1 loading
* 4: pre stage 1, initialize time variable for time constant blending
* 3: initial -> allows initial loading of textures
* 2: texture has finished changed, dont change it anymore
* 1: initiate texture change
* 0: don't change any texture */
int change_it = 0;
signed int offset = -1;
int check_id = WAIT_TIME*100+1;

typedef struct {
pthread_mutex_t read_mutex; // synchronize access to reading flag
int reading; // 0 = not reading , 1 = reading , 2 = finished reading
char *content; // content of file
char *file; // file to read
} struct_file_content;

struct_file_content struct_data_file[4];

char *file_content[4];

// temperature in abu dhabi
#define file1 "/home/tias/repository/data/temp_ad.txt"

// temperature in irsch
#define file2 "/home/tias/repository/data/temp_ir.txt"

// change EUR / AED
#define file3 "/home/tias/repository/data/change.txt"

// monitoring data used to color cubes
#define file4 "/home/tias/repository/data/summary.txt"

void change_or_not(signed int* offset, int* check_id, int* change_it) {

if ( *offset == -1 ) {
*offset = (signed int) ( time(NULL) ) % WAIT_TIME;
}

int delta = (int) ( ( ( (long) time(NULL) ) - *offset ) % WAIT_TIME );
int delta_id = (int) ( (long) time(NULL) % (WAIT_TIME * 100) );

if ( *check_id > WAIT_TIME*100 ) *check_id = delta_id;

if ( delta == 0 && *check_id != delta_id && *change_it == 0 ) {
//*change_it = 4;
*change_it = 1;
*check_id = delta_id;
}

if ( delta == 0 && *check_id != delta_id && *change_it == 2 ) *change_it = 0;

}

void pretend_texture_blending ( int* change_it ) {
static old_change_it = 0;
static int ori = 0;
if ( old_change_it == 0 && *change_it == 1 ) {
ori = time(NULL);
}
if ( time(NULL) > ori && *change_it == 1 ) {
ori = time(NULL);
*change_it = 2;
}
old_change_it = *change_it;
}

void *thread_read_file(void *data) {

struct_file_content *thisdata = data;
int mutex_res;
long length;
char *thiscontent = NULL;

// lock mutex
mutex_res = pthread_mutex_lock(&thisdata->read_mutex);

if (mutex_res != 0) {
fprintf(stderr, "thread_read_file() failed to acquire mutex: %s\n", strerror(mutex_res));
pthread_exit(NULL);
} else {
fprintf(stdout, "thread_read_file: mutex locked for file: %s\n",thisdata->file);
}
// end locking procedure

// let's open the file now
FILE *f = fopen(thisdata->file, "r");

// let's get the size of the file and bounce if it is too large
// if size is acceptable, read the file into memory
if (f) {
fseek(f, 0, SEEK_END);
length = ftell(f);
fseek (f, 0, SEEK_SET);

if (length > 39) {
fprintf(stderr, "file %s is too big\n", thisdata->file);
pthread_exit(NULL);
}

thiscontent = (char*)malloc((length+1)*sizeof(char));

if (thiscontent) {
fread(thiscontent, 1, length, f);
} else {
perror("malloc(3) error");
pthread_exit(NULL);
}

fclose(f);

// puzzling result is here :
// first run with the 4 threads always work fine
// next runs will randomly display mixed values / other memory locations

fprintf(stdout,"thiscontent: %s length was %d for file %s\n",thiscontent,length,thisdata->file);

} else {
fprintf(stderr, "cannot open file %s\n", thisdata->file);
pthread_exit(NULL);
}
// file read and fd closed

// free old allocation of this content
free(thisdata->content);
thisdata->reading = 2;
// assign new result to newly freed char*
thisdata->content = thiscontent;

// unlock mutex as everything has been updated

mutex_res = pthread_mutex_unlock(&thisdata->read_mutex);

if (mutex_res != 0) {
fprintf(stderr, "thread_read_file() failed to release mutex: %s\n", strerror(mutex_res));
pthread_exit(NULL);
} else {
fprintf(stdout,"thread_read_file: mutex unlocked for file: %s\n", thisdata->file);
}
// end unlock mutex procedure

return NULL;
}

int main(int argc, char** argv) {

static int init = 1;

int p,q,r,curtime;
float X,Y;
static int data_update_done[4] = { 0,0,0,0 };

static pthread_t thread_file[4];
static int thread_res[4] = { 0,0,0,0 };

static char *files[4];
files[0] = (char*)malloc(sizeof(char)*strlen(file1));
files[1] = (char*)malloc(sizeof(char)*strlen(file2));
files[2] = (char*)malloc(sizeof(char)*strlen(file3));
files[3] = (char*)malloc(sizeof(char)*strlen(file4));

int mutex_err[4];

// init = 1
// => launches the 4 threads for reading the 4 files
//
if ( init == 1 ) {

strcpy(files[0],file1);
strcpy(files[1],file2);
strcpy(files[2],file3);
strcpy(files[3],file4);

for ( p = 0 ; p < 4 ; p++ ) {

mutex_err[p] = pthread_mutex_init(&struct_data_file[p].read_mutex, NULL);

if (mutex_err[p] != 0 ) {
fprintf(stderr, "pthread_mutex_init(3) error: %s\n", strerror(mutex_err[p]));
exit(EXIT_FAILURE);
}

struct_data_file[p].reading = 1;
struct_data_file[p].content = NULL;
struct_data_file[p].file = files[p];

thread_res[p] = pthread_create(&thread_file[p], NULL, thread_read_file, &struct_data_file[p]);

}

init = 0;

}

// main loop
while (1) {

change_or_not(&offset, &check_id, &change_it);
usleep(50000);
fprintf(stdout,".%u.",change_it);
fflush(stdout);
pretend_texture_blending(&change_it);

for ( p = 0 ; p < 4 ; p++ ) { // updating data if ready, destroying mutex when done, etc...

// lock mutex
mutex_err[p] = pthread_mutex_lock(&struct_data_file[p].read_mutex);

if ( mutex_err[p] != 0 ) {
fprintf(stderr, "pthread_mutex_lock(3) error: %s\n",strerror(mutex_err[p]));
exit(EXIT_FAILURE);
}
// end lock mutex

// data update routine
// is data ready: check variable 'reading' from the struct_data_file struct
// 2 -> yes : update + destroy mutex
// 1 or 0 -> no : unlock mutex

if ( struct_data_file[p].reading == 2 ) { // data is ready
if (file_content[p]) free(file_content[p]);
file_content[p] = (char *)malloc(strlen(struct_data_file[p].content)*sizeof(char));
strcpy(file_content[p],struct_data_file[p].content);
struct_data_file[p].reading = 0;
mutex_err[p] = pthread_mutex_unlock(&struct_data_file[p].read_mutex);
if (mutex_err[p] != 0) {
fprintf(stderr, "Warning: Error destroying mutex: %s\n", strerror(mutex_err[p]));
}
} else {
mutex_err[p] = pthread_mutex_unlock(&struct_data_file[p].read_mutex);
if ( mutex_err[p] != 0 ) {
fprintf(stderr, "pthread_mutex_unlock(3) error: %s\n",strerror(mutex_err[p]));
exit(EXIT_FAILURE);
}
}
// end checking if data is ready
}

if ( change_it == 1 ) {
for ( p = 0 ; p < 4 ; p++ ) {
if ( struct_data_file[p].reading == 0 ) {
if ( data_update_done[p] == 0 ) {
thread_res[p] = pthread_create(&thread_file[p], NULL, thread_read_file, &struct_data_file[p]);
data_update_done[p] = 1;
}
}
}
}

if ( change_it == 2 ) {
for ( p = 0 ; p < 4 ; p++ ) {
data_update_done[p] = 0;
}
}

// end main loop
}
// end main
}

输出为

thiscontent: abu dhabi:35.6 length was 14 for file /home/tias/repository/data/temp_ad.txt
thread_read_file: mutex unlocked for file: /home/tias/repository/data/temp_ad.txt
thread_read_file: mutex locked for file: /home/tias/repository/data/summary.txt
thiscontent: AED/euro:4.09534 length was 16 for file /home/tias/repository/data/change.txt
thiscontent: 11111 length was 5 for file /home/tias/repository/data/summary.txt
thread_read_file: mutex unlocked for file: /home/tias/repository/data/summary.txt
thread_read_file: mutex unlocked for file: /home/tias/repository/data/change.txt
.1..1..1..1..1..1..1..1..1..1..1..1..1..1..1..1..1..1..2..2..2..2..2..2..2..2..2..2..2..2..2..2..2..2..2..2..2..2..0..1.thread_read_file: mutex locked for file: /home/tias/repository/data/temp_ir.txt
thread_read_file: mutex locked for file: /home/tias/repository/data/temp_ad.txt
thread_read_file: mutex locked for file: /home/tias/repository/data/summary.txt
thread_read_file: mutex locked for file: /home/tias/repository/data/change.txt
thiscontent: AED/euro:4.09534 length was 16 for file /home/tias/repository/data/change.txt
thread_read_file: mutex unlocked for file: /home/tias/repository/data/change.txt
thiscontent: abu dhabi:35.6 length was 14 for file /home/tias/repository/data/temp_ad.txt
thread_read_file: mutex unlocked for file: /home/tias/repository/data/temp_ad.txt
thiscontent: irsch:14.6.09534 length was 10 for file /home/tias/repository/data/temp_ir.txt
thread_read_file: mutex unlocked for file: /home/tias/repository/data/temp_ir.txt
thiscontent: 1111 length was 5 for file /home/tias/repository/data/summary.txt
thread_read_file: mutex unlocked for file: /home/tias/repository/data/summary.txt
.1..1..1..1..1..1..1..1..1..1..1..1..1..1..1..1..1..1..2..2..2..2..2..2..2..2..2..2..2..2..2..2..2..2..2..2..2..2..0..1.thread_read_file: mutex locked for file: /home/tias/repository/data/temp_ad.txt
thread_read_file: mutex locked for file: /home/tias/repository/data/temp_ir.txt
thread_read_file: mutex locked for file: /home/tias/repository/data/summary.txt
thread_read_file: mutex locked for file: /home/tias/repository/data/change.txt
thiscontent: irsch:14.6.09534 length was 10 for file /home/tias/repository/data/temp_ir.txt
thread_read_file: mutex unlocked for file: /home/tias/repository/data/temp_ir.txt
thiscontent: abu dhabi:35.6 length was 14 for file /home/tias/repository/data/temp_ad.txt
thread_read_file: mutex unlocked for file: /home/tias/repository/data/temp_ad.txt
thiscontent: AED/euro:4.09534 length was 16 for file /home/tias/repository/data/change.txt
thread_read_file: mutex unlocked for file: /home/tias/repository/data/change.txt
thiscontent: 1111 length was 5 for file /home/tias/repository/data/summary.txt
thread_read_file: mutex unlocked for file: /home/tias/repository/data/summary.txt

这 4 个文件的内容是恒定的。

前 4 个结果始终是正确的(4 个线程读取 4 个文件,据我所知并且我已经做了很多测试,第一组结果始终是正确的)。

但是,当显示变量 thiscontent 时(第一次运行后),我会得到额外的输出甚至更少的输出(文件 summary.txt 包含 11111)

例如:我得到了这个内容:irsch:14.6.09534我应该得到这个内容:irsch:14.6

还有我应该一直得到:此内容:11111 长度为 5但有时我得到此内容:1111 长度为 5

我不明白为什么,也无法修复它。我对变量 thiscontent 是自动的这一事实感到困惑,因此应该在每次函数调用时进行初始化。但输出显示不同。

这可能是内存分配问题,但我目前不知道。

非常感谢任何帮助。

PS:你可能会发现一些无用的代码,这是因为主程序是我写的opengl屏保,有1000行长。

我发布的代码是此屏幕保护程序的摘录,重现了该问题,但没有大量无用的代码用于此故障排除。

谢谢

PS no2:您可以将此代码复制/粘贴到名为threads.c的文件中并使用以下命令进行编译:

gcc -o threads threads.c -lpthread -D_REENTRANT

最佳答案

您正在将文件内容打印为字符串,但尚未向其中添加 nul 终止符。因此,字符串不会终止 - 您看到的额外输出是内存中超出内容的垃圾。

你所在的地方:

        fread(thiscontent, 1, length, f);

您还需要添加 nul 终止符:

        thiscontent[length] = 0;

关于c线程并发和内存混合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32424101/

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