本文介绍了C语言中的多线程和多任务处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个运行两个线程(pthreads)的程序。代码在某些部分运行良好,但在某些部分,结果就像符号。



是否有线程专家或社区,我可以发布我的问题,专门用于多线程?



我真的需要帮助,谢谢你提前。





这是一部分有问题的代码:



I am writing a program that runs two threads (pthreads). The code runs fine on some parts but in some parts the results are like symbols.

Is there an expert on threads or like a community that I can post my issue which are dedicated to multi-threading?

I really need help, thank you in advance.


This is the part of the code that has the problem:

void Encryption()
{
	int i = 0, j = 0, rc=0;
	ourStruct args[Chunks];
	pthread_t thread[Threads];

	ReadOurFile();
	counter = 0;
	for (j = 0; j <= numOfChunks; j++)
	{
		for (i = 0; i < numOfRows; ++i)
		{
			args[j].plainText[i] = InPut[j][i];
			args[j].FinalKey[i] = FinalKey[j][i];
		}
		args[j].index = counter;
		counter++;
	}
	for (j = 0; j <= numOfChunks; j=j+2)
	{
		rc = pthread_create(&thread[0], NULL, Method_Encryption, &args[j]);
		rc = pthread_create(&thread[1], NULL, Method_Encryption, &args[j+1]);
		rc = pthread_join(thread[0], NULL);
		rc = pthread_join(thread[1], NULL);
	}
	//writing the output to a file
}

The method is:
void * Method_Encryption(void *arguments){
.
.
.
StructInside *args = (StructInside *)arguments;
	//setting the received arguments into plaintext and key
	for (i = 0; i < numOfRows; ++i)
	{
		plainText[i] = args->plainText[i];
		FinalKey[i] = args->FinalKey[i];
	}
.
.
.
//store results
	for (i = 0; i < numOfRows; ++i)
		OutPut[args->index][i] = plainText[i];
}



输出填充在方法内的输出数组中。数组按订单编制索引。

numOfChunks ==我正在从文件中读取的块数。例如:如果文件大小为100个字符,每个块大小为5个字符,则:

numOfChunks = 100/5

我们也尝试使用互斥锁在struct中并初始化互斥锁并将其锁定在方法内,然后解锁并销毁互斥锁​​但它没有工作,或者我们没有正确实现它。


The output is filled inside an array of output inside the method. The array is indexed by the order.
numOfChunks ==the number of chunks I'm reading from the file. For example: if the file is of size 100 characters, and each chunk will be of size 5 characters, then:
numOfChunks=100/5
We also tried using mutex inside the struct and initialize the mutex and lock it inside the method and afterwards unlocking and destroying the mutex but it didn’t work, or maybe we didn’t implement it correctly.

推荐答案


for (j = 0; j <= numOfChunks; j++) { /* ... */ }



应该是:


Should be:

for (j = 0; j < numOfChunks; j++) { /* ... */ }



这是因为索引 j 等于 numOfChunks ,您要通过数组 args 分配的内存进行寻址。



-SA


This is because in index j equals to numOfChunks, you are addressing past the memory allocated by the array args.

—SA



这篇关于C语言中的多线程和多任务处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 01:46