gpt4 book ai didi

c - 为什么这个多线程 C 程序给我段错误?

转载 作者:太空宇宙 更新时间:2023-11-04 05:43:56 25 4
gpt4 key购买 nike

<分区>

我的意图是使用多线程转置两个文件。但是下面的程序给我段错误。

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


void *a_to_temp( void *filea);
void copyFile( FILE *in, FILE *out );
void *temp_to_b( void *fileb);
void *b_to_a(void *ab);

struct files{
char a[80];
char b[80];
} ab;

pthread_mutex_t temptob = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t btoa = PTHREAD_MUTEX_INITIALIZER;

main(int argc, char **argv)
{
fprintf(stderr, "in main");

pthread_t thread1, thread2, thread3;
strcpy( ab.a, argv[1]);
strcpy(ab.b, argv[2]);

int iret1, iret2, iret3;

pthread_mutex_lock( &temptob );
pthread_mutex_lock( &btoa );

iret1 = pthread_create( &thread1, NULL, a_to_temp, (void*) &argv[1]);

iret2 = pthread_create( &thread2, NULL, b_to_a, (void*) &ab);

iret3 = pthread_create( &thread3, NULL, temp_to_b, (void*) &argv[2]);


pthread_join( thread1, NULL);
pthread_join( thread2, NULL);
pthread_join( thread3, NULL);

exit(0);
}


void *a_to_temp( void *filea) {
FILE *a = fopen((char *)filea, "r");
FILE *f = fopen( "temp", "w");
copyFile( a , f);
fclose(f);
fclose( a);
pthread_mutex_unlock( &temptob );
}

void *temp_to_b( void *fileb) {
pthread_mutex_lock( &temptob );
FILE *b = fopen((char *)fileb, "r");
FILE *f = fopen( "temp", "r");
copyFile( f, b);
fclose(f);
pthread_mutex_unlock( &btoa );
}

void *b_to_a(void *ab) {
pthread_mutex_lock( &btoa );
FILE *a = fopen(((struct files *) ab)->a, "w"); //
FILE *b = fopen(((struct files *) ab)->b, "r");//
fprintf(stderr, "c files opened");
copyFile( b, a);
fclose(a);
fclose(b);
}

void copyFile( FILE *in, FILE *out) {
char ch;
while(!feof(in)) {
ch = getc(in);
if(!feof(in)) putc(ch, out);
}
}

我通过打印值测试了代码,直到主函数结束。我猜错误应该在其中一个函数中。

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