当前位置: 技术问答>linux和unix
使用pthread多线程文件IO的问题
来源: 互联网 发布时间:2016-04-08
本文导语: 问题是:开了两个线程,2号线程正常退出,1号线程和主线程都挂在join那里不动了,程序死在那里 我用GDB调试的时候,发现主线程和1号线程都在 _kernel_vsyscall()中就不动了 代码就是从一个文件中读入每一行,然后写...
问题是:开了两个线程,2号线程正常退出,1号线程和主线程都挂在join那里不动了,程序死在那里
我用GDB调试的时候,发现主线程和1号线程都在 _kernel_vsyscall()中就不动了
代码就是从一个文件中读入每一行,然后写入到另一个文件中
急,请高手指点!感激不尽
代码如下:
#include
#include
#include
using namespace std;
const int NUM_THREADS = 2;
const int MAX_CHAR_A_LINE = 1000;
FILE *inFile = NULL;
FILE *outFile = NULL;
pthread_mutex_t inMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t outMutex = PTHREAD_MUTEX_INITIALIZER;
bool over = false;
;
void *fileIoThreads( void * args )
{
int * num = (int *)((void **)args)[0];
char* str = (char *)((void**)args)[1];
char line[MAX_CHAR_A_LINE] = {0};
while(1)
{
pthread_mutex_lock( &inMutex );
if ( over || !fgets(line,MAX_CHAR_A_LINE,inFile)) {
break;
}
pthread_mutex_unlock(&inMutex);
pthread_mutex_lock( &outMutex );
fprintf( outFile, "%st%dt%st", line, *num, str );
printf( "%dt%s", *num, line );
pthread_mutex_unlock( &outMutex );
}
fflush( outFile );
over = true;
return 0;
}
int main()
{
int i, ret;
inFile = fopen( "test3", "r");
outFile = fopen( "out", "w");
pthread_t a_thread[NUM_THREADS];
char buf[] = "func";
void* arg[2];
arg[1] = buf;
for( int i = 0; i
我用GDB调试的时候,发现主线程和1号线程都在 _kernel_vsyscall()中就不动了
代码就是从一个文件中读入每一行,然后写入到另一个文件中
急,请高手指点!感激不尽
代码如下:
#include
#include
#include
using namespace std;
const int NUM_THREADS = 2;
const int MAX_CHAR_A_LINE = 1000;
FILE *inFile = NULL;
FILE *outFile = NULL;
pthread_mutex_t inMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t outMutex = PTHREAD_MUTEX_INITIALIZER;
bool over = false;
;
void *fileIoThreads( void * args )
{
int * num = (int *)((void **)args)[0];
char* str = (char *)((void**)args)[1];
char line[MAX_CHAR_A_LINE] = {0};
while(1)
{
pthread_mutex_lock( &inMutex );
if ( over || !fgets(line,MAX_CHAR_A_LINE,inFile)) {
break;
}
pthread_mutex_unlock(&inMutex);
pthread_mutex_lock( &outMutex );
fprintf( outFile, "%st%dt%st", line, *num, str );
printf( "%dt%s", *num, line );
pthread_mutex_unlock( &outMutex );
}
fflush( outFile );
over = true;
return 0;
}
int main()
{
int i, ret;
inFile = fopen( "test3", "r");
outFile = fopen( "out", "w");
pthread_t a_thread[NUM_THREADS];
char buf[] = "func";
void* arg[2];
arg[1] = buf;
for( int i = 0; i