如何在多个线程C从线程返回时立即获取返回值



第一次提问时,希望能有成效:(我有10个线程在运行,我需要main来打印2件事:

  1. 从线程返回的值
  2. 当所有线程都完成时,以发送到线程的相同顺序打印所有值的矢量

现在,程序打印"--->quot;从函数来看,这意味着它完成了踏板,但我需要它从main打印它们。

#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
//sem_t mutex;
void *myThread(void *args)
{
int argptr=do123(*(int*)args);
printf("--->%dn",argptr);
//  sem_wait(&mutex);
//*(int*)args=do123((int)args);
return (void*)argptr;
}
int main()
{
int nums[10]={17,65,34,91,92,93,33,16,22,75};
int TemPnums[10]={17,65,34,91,92,93,33,16,22,75};
int res[10]={0};
//pthread_t t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
pthread_t theads[10];
for (int i = 0;  i < 10; i++) {
res[i]=nums[i];
pthread_create(&theads[i], NULL, myThread, &TemPnums[i]);
}
// pthread_join(&theads[10], &status);
for (int i = 0;  i < 10; i++) {
void *status;
pthread_join(theads[i], &status);
res[i]=(int)status;
}
for (int i = 0;  i < 10; i++) {
printf("%dn",res[i]);
}

}
int do123(int num)
{
int k=0;
while(num!=1){
if(num%2==1){
num=num*3+1;
k++;
}else{
num=num/2;
k++;
}
}
return k;
}

输出:

--->12
--->92
--->27
--->13
--->17
--->17
--->26
--->14
--->4
--->15
12
27
13
92
17
17
26
4
15
14

C中线程连接的时间不受同一线程执行的时间的影响,也不受其顺序的决定。这意味着在我的系统中,一个线程在10个线程池中执行和加入的顺序可能因系统而异。例如,使用这个修改后的代码版本(请参阅文章底部的更改说明(:

#include <pthread.h>
#include <semaphore.h>
#include <stdio.h>
#include <unistd.h>
#include <cstdint>
//sem_t mutex;
int do123(int); // Added (1)
void *myThread(void *args)
{
size_t argptr = do123(*(int *)args);
printf("--->%dn", argptr);
//  sem_wait(&mutex);
//*(int*)args=do123((int)args);
return (void *)argptr;
}
int main()
{
int nums[10]     = {17, 65, 34, 91, 92, 93, 33, 16, 22, 75};
int TemPnums[10] = {17, 65, 34, 91, 92, 93, 33, 16, 22, 75};
int res[10]      = {0};
//pthread_t t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
pthread_t theads[10];
for (int i = 0; i < 10; i++)
{
res[i] = nums[i];
pthread_create(&theads[i], NULL, myThread, &TemPnums[i]);
}
// pthread_join(&theads[10], &status);
for (int i = 0; i < 10; i++)
{
void *status;
pthread_join(theads[i], &status);
res[i] = (size_t)status;
}
for (int i = 0; i < 10; i++)
{
printf("%dn", res[i]);
}
}
int do123(int num)
{
int k = 0;
while (num != 1)
{
if (num % 2 == 1)
{
num = num * 3 + 1;
k++;
}
else
{
num = num / 2;
k++;
}
}
return k;

我得到输出:

--->12
--->27
--->13
--->92
--->17
--->17
--->26
--->4
--->15
--->14
12
27
13
92
17
17
26
4
15
14

如果你的目标是确保线程以在辅助函数中分配其值的相同顺序加入主函数中的数组,我建议在一个线程分配了其值后实现一种阻止后续线程的方法。为了做到这一点,你可以使用信号量或互斥实现一个系统。

信号量文档:https://www.tutorialspoint.com/how-to-use-posix-semaphores-in-c-language

关于互斥的文档:https://www.tutorialspoint.com/deadlock-with-mutex-locks

简而言之,流程应该是当一个线程进入do123((时,锁定所有其他线程进入该函数。让该线程上的所有工作都完成,并让它从函数返回,并分配给数组中相应的索引。在此之后,您应该解锁下一个线程并重复。

我建议阅读一下,以便更好地了解线程是如何工作的。祝你好运

更改说明:

(1( 在代码中使用函数之前,必须添加函数声明。你在下面调用函数的地方有函数的定义。编译器不知道这个函数,因为它从";自上而下";。

由于大小取决于您的操作系统(16位、32位等(,将类型void*强制转换为int会丢失精度。我将它们更改为size_t结构,这将确保非负值,并解释精度的损失。

最新更新