[英]segmentation fault in multithreading program
I'm trying to multiply two matrices using multithreading. 我正在尝试使用多线程将两个矩阵相乘。 But the code is giving segmentation fault.
但是代码给分段错误。 I am passing the row number and column number using a structure.
我正在使用结构传递行号和列号。 The matrices a and b are made global.
使矩阵a和b全局。 This is not entirely correct way to do it, but I'm just trying to understand how multithreading stuff works.
这并不是完全正确的方法,但我只是想了解多线程工作原理。
#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;
}
How can I fix the segmentation fault? 如何修复细分错误?
First thing, you need to wait for all the threads to finish (in main
): 首先,您需要等待所有线程完成(在
main
):
for (i = 0; i < count; ++i) {
pthread_join(p_thread[i],NULL);
}
Failure to do so will crash your app as the thread continue to work why the application is being destroyed. 否则,由于线程继续工作,导致应用程序被破坏,因此失败会使您的应用程序崩溃。 You need to call
pthread_join
after you create all the threads. 创建所有线程后,需要调用
pthread_join
。
If you create a thread and immediately call pthread_join
you execution is serial as one thread is active at any given time. 如果创建线程并立即调用
pthread_join
,则执行是串行的,因为在任何给定时间都有一个线程处于活动状态。
Explanation: 说明:
"join" means: "wait for thread to finish execution". “ join”的意思是:“等待线程完成执行”。 A thread finishes execution when either it returns from it's entry point function (function passed to
pthread_create
) or it calls pthread_exit
. 当线程从其入口点函数(传递给
pthread_create
函数)返回或调用pthread_exit
时,该线程完成执行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.