gpt4 book ai didi

c - 多线程程序中的段错误

转载 作者:太空宇宙 更新时间:2023-11-04 02:52:31 25 4
gpt4 key购买 nike

我正在尝试使用多线程将两个矩阵相乘。但是代码给出了段错误。我正在使用结构传递行号和列号。矩阵 a 和 b 是全局的。这不是完全正确的方法,但我只是想了解多线程的工作原理。

#include <pthread.h>    
#include <unistd.h>
#include <iostream>
using namespace std;
int a[3][3]={{1,2,3},{4,5,6},{7,8,9}};
int b[3][2]={{1,2},{3,4},{5,6}};
int c[3][2];
int k =3;
struct thread_data{
int m;
int n;
};
void* do_loop(void* threadarg)
{
int p,q;
struct thread_data *my_data;

my_data = (struct thread_data *) threadarg;
int i=my_data->m;
int j=my_data->n;
c[i][j]=0;

for(q=0;q<k;q++)
{
c[i][j]=c[i][j]+a[i][q]*b[q][j];
}

pthread_exit(NULL);
}
int main(int argc, char* argv[])
{
int i,j,k;
struct thread_data td[6];

int thr_id;
pthread_t p_thread[6];
int count=0;
for(i=0;i<3;i++)
for(j=0;j<2;j++)
{
td[count].m=i;
td[count].n=j;

thr_id = pthread_create(&p_thread[count], NULL, do_loop, (void*)&td[count]);
// pthread_join(p_thread[count],NULL);
count++;
}
return 0;
}

如何修复段错误?

最佳答案

首先,您需要等待所有线程完成(在 main 中):

for (i = 0; i < count; ++i) {
pthread_join(p_thread[i],NULL);
}

如果不这样做,您的应用程序将崩溃,因为线程继续工作,导致应用程序被销毁。创建所有线程后,您需要调用 pthread_join

如果您创建一个线程并立即调用 pthread_join,您的执行是串行的,因为一个线程在任何给定时间都处于事件状态。

解释:

“加入”的意思是:“等待线程完成执行”。当线程从其入口点函数(传递给 pthread_create 的函数)返回或调用 pthread_exit 时,线程完成执行。

关于c - 多线程程序中的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20630734/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com