linux下C多线程编程,为每个文件创建一个线程,转换内容大小写
不知道为什么,文件内容没改变#define_XOPEN_SOURCE700#include<pthread.h>#include<stdio.h>#include<std...
不知道为什么,文件内容没改变
#define _XOPEN_SOURCE 700
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void* thr_convert(void* arg)
{
FILE* fp1, *fp2;
int c = 1;
fp1= fopen ((char*)arg, "r");
fp2= fopen ((char*)arg, "r+");
if ((fp1== NULL) || (fp2== NULL)) {
perror ("fopen");
exit (1);
}
while (c !=EOF) {
c=fgetc(fp1);
if (c!=EOF)
fputc(toupper(c),fp2);
}
fclose (fp1);
fclose (fp2);
return ((void*)0);
}
int main(int argc, char ** argv)
{
pthread_t tid;
int i;
for(i=1; i<argc; i++)
{
if(pthread_create(&tid, NULL, thr_convert, (void*)argv[i]) != 0)
{
perror("pthread_create");
exit(1);
}
}
return EXIT_SUCCESS;
} 展开
#define _XOPEN_SOURCE 700
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
void* thr_convert(void* arg)
{
FILE* fp1, *fp2;
int c = 1;
fp1= fopen ((char*)arg, "r");
fp2= fopen ((char*)arg, "r+");
if ((fp1== NULL) || (fp2== NULL)) {
perror ("fopen");
exit (1);
}
while (c !=EOF) {
c=fgetc(fp1);
if (c!=EOF)
fputc(toupper(c),fp2);
}
fclose (fp1);
fclose (fp2);
return ((void*)0);
}
int main(int argc, char ** argv)
{
pthread_t tid;
int i;
for(i=1; i<argc; i++)
{
if(pthread_create(&tid, NULL, thr_convert, (void*)argv[i]) != 0)
{
perror("pthread_create");
exit(1);
}
}
return EXIT_SUCCESS;
} 展开
2个回答
展开全部
你main里创建完线程就直接退出了,线程还没来的及干活就结束当然不行了。需要加pthread_join等待,像下面这样:
int main(int argc, char ** argv)
{
pthread_t tid[10];
int i;
for(i=1; i<argc; i++)
{
if(pthread_create(&tid[i], NULL, thr_convert, (void*)argv[i]) != 0)
{
perror("pthread_create");
exit(1);
}
}
for(i=1; i<argc; i++)
pthread_join(tid[i],NULL);
return EXIT_SUCCESS;
}
int main(int argc, char ** argv)
{
pthread_t tid[10];
int i;
for(i=1; i<argc; i++)
{
if(pthread_create(&tid[i], NULL, thr_convert, (void*)argv[i]) != 0)
{
perror("pthread_create");
exit(1);
}
}
for(i=1; i<argc; i++)
pthread_join(tid[i],NULL);
return EXIT_SUCCESS;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询