【发布时间】:2017-10-23 00:39:04
【问题描述】:
这是一个操作系统编程作业。我正在尝试读取 n 个文件,使用线程在每个文件中搜索特定字符的出现次数。
./mycount j new.txt some.txt here.txt hello.txt
我的测试代码的输出应该是:
argumentCount: 6
threadCount: 4
pthread_create() for thread 0 returns: 0
Thread 1
pthread_create() for thread 1 returns: 0
Thread 2
pthread_create() for thread 2 returns: 0
Thread 3
pthread_create() for thread 3 returns: 0
Thread 4
但是 mycount 的每次执行都是不同的,最后一个线程通常不会执行/打印。要么这样,要么他们会偶尔打印,串联打印,等等。
我正在尝试使用互斥锁来确保我的数据的完整性,但我不确定幕后究竟发生了什么。
如何确保每次都以相同的方式完成?最后一个线程总是返回0,但有时它不会完全执行我给它的函数。
代码:
//GLOBALS
int occurrences = 0;
//PROTOTYPES
void *scanFile( void *filePtr );
//Initialize space for mutex.
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//Receive arguments from .exe call
void main ( int argumentCount, char *argumentVariables[] )
{
//Exit if argumentCount is > 50.
if (argumentCount > 50)
{
perror("Too many arguments. Enter less than 50.\n");
exit(EXIT_FAILURE);
}
printf("argumentCount: %d \n", argumentCount);
//Instantiate variables.
//i - iterator
//*newCommand - Used to hold string value of first command entered.
//*newVector - Used to hold string of the rest of the commands. Is a vector.
int i;
char *searchCharacter;
char *newVector[argumentCount];
//Iterate through command line arguments and split them.
for (i = 0; i < argumentCount; i++)
{
searchCharacter = argumentVariables[1];
if (i < argumentCount - 1)
{
newVector[i] = argumentVariables[1 + i];
}
else
{
newVector[i] = NULL;
}
}
//Exit if newest command is NULL.
if (searchCharacter == NULL)
{
perror("No character entered!\n");
exit(EXIT_FAILURE);
}
int threads = argumentCount - 2;
printf("threadCount: %d \n", threads);
pthread_t * thread = malloc(sizeof(pthread_t)*threads);
for (int i = 0; i < threads; i++)
{
int ret;
char *message = "Thread";
ret = pthread_create(&thread[i], NULL, scanFile, (void*) message);
if (ret != 0)
{
printf("Error - pthread_create() return code: %d\n", ret);
exit(EXIT_FAILURE);
}
printf("pthread_create() for thread %d returns: %d\n", i, ret);
}
exit(EXIT_SUCCESS);
}
void *scanFile( void *filePtr )
{
pthread_mutex_lock( &mutex );
char *message;
message = (char *) filePtr;
occurrences += 1;
printf("%s %d\n", message, occurrences);
pthread_mutex_unlock( &mutex );
}
【问题讨论】:
-
加入线程的代码在哪里?为什么确保“所有线程启动并完成工作”很重要?
-
我不确定如何加入 n 个线程。此外,确保它们全部执行对我来说很重要,因为将来我需要每个线程扫描文件以查找特定字符的多次出现。
-
@AustinHeath,加入 n 个线程只是一次加入一个。正在发生的事情是您的进程在所有线程完成之前就退出了,因为您没有采取任何措施来防止这种情况发生。启动它们后,您将终止进程(及其所有线程)。
-
成功了!谢谢!发布解决方案。 @KenThomases
标签: c linux multithreading