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. 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):
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.
If you create a thread and immediately call pthread_join you execution is serial as one thread is active at any given time.
Explanation:
"join" means: "wait for thread to finish execution". A thread finishes execution when either it returns from it's entry point function (function passed to pthread_create) or it calls pthread_exit.
Related
So i have the following problem: Implement a program that gets as arguments a file name followed by words. For each word, create a separate thread that counts its appearances in the given file.Print out the sum of the appearances of all words.
I'm also not sure if my code is really formatted correctly. I'm trying to figure out how to get each word to be counted in the given text file. I am trying to test out this code but I am getting a couple errors from it, the biggest being a segmentation error. If you have any pointers or advice or help, please let me know.
my code is:
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <pthread.h>
pthread_mutex_t mtx; // used by each of the three threads to prevent other threads from accessing global_sum during their additions
int global_sum = 0;
typedef struct{
char* word;
char* filename;
}MyStruct;
void *count(void*str)
{
MyStruct *struc;
struc = (MyStruct*)str;
const char *myfile = struc->filename;
FILE *f;
int count=0, j;
char buf[50], read[100];
// myfile[strlen(myfile)-1]='\0';
if(!(f=fopen(myfile,"rt"))){
printf("Wrong file name");
}
else
printf("File opened successfully\n");
for(j=0; fgets(read, 10, f)!=NULL; j++){
if (strcmp(read[j],struc->word)==0)
count++;
}
printf("the no of words is: %d \n",count);
pthread_mutex_lock(&mtx); // lock the mutex, to prevent other threads from accessing global_sum
global_sum += count; // add thread's count result to global_sum
pthread_mutex_unlock(&mtx); // unlock the mutex, to allow other threads to access the variable
}
int main(int argc, char* argv[]) {
int i;
MyStruct str;
pthread_mutex_init(&mtx, NULL); // initialize mutex
pthread_t threads[argc-1]; // declare threads array
for (i=0;i<argc-2;i++){
str.filename = argv[1];
str.word = argv[i+2];
pthread_create(&threads[i], NULL, count, &str);
}
for (i = 0; i < argc-1; ++i)
pthread_join(threads[i], NULL);
printf("The global sum is %d.\n", global_sum); // print global sum
pthread_mutex_destroy(&mtx); // destroy the mutex
return 0;
}
The second good bit of advice for today is to look carefully at the warnings that your compiler gives you and take heed of them. strcmp(read[j],struc->word) Your compiler must have warned you that that is wrong. You are passing a single char as the first parameter instead of const char *. That'll almost certainly result in a seg fault. – kaylum
I have to design a multi-threaded application involved with the consumer-producer problem. So far, I've been trying to get the Pthreads to work correctly before I try to implement my solution. But, my program won't even load up the the function on my pthread. I'm not sure what I'm doing wrong here.
#include <pthread.h>
#include <stdlib.h>
#include <stdio.h>
void* Producer(void *arg)
{
printf("\nEntered Producer\n");
int i, item, index;
index = (int)arg;
FILE *f = fopen(bookorders, "r");
char c = fgetc(f);
int z =0;
while (c!=EOF) {
char * buffer = (char *)malloc(1000);
while (c!='\n') {
*(buffer+z) = c;
z++;
c = fgetc(f);
}
char delim[2] = "|";
printf("%s\n", buffer);
}
}
int main(int argc, const char * argv[])
{
pthread_t Produc;
pthread_create(&Produc, NULL, Producer, NULL);
return 0;
}
I guess my big question is what is the proper process of creating a pthread and then getting it to run a function, which in this case is my Producer function
What's happening here is your main thread calls pthread_create and just returns and since the main thread exits, your Production thread also exits. What you need to do is, instruct the main thread to wait for the Produc thread to finish executing.
int main(){
//Call pthread_create
pthread_join(Produc, NULL) ;
return 0;
}
I'm having a trouble passing a struct pointer into a function because I'm a bit confused with those pointers and references. I want to modify the thread.thread_num value from the thread_startfunction.
#include <stdio.h>
#include <stdlib.h> //malloc, free
#include <pthread.h>
#define N 5
// void *malloc(size_t);
struct thread {
pthread_t thread_id;
int thread_num;
// int thread_sum;
};
void *thread_start(void *thread)
{
struct thread *my_data;
my_data = (struct thread *)thread;
printf("num T: %i\n", my_data->thread_num);
my_data->thread_num=4;
printf("num T: %i\n", my_data->thread_num);
return NULL;
}
int main(int argc, char *argv[])
{
int i;
struct thread pthread_data;
struct thread *thread = &pthread_data;
thread->thread_num=2;
pthread_create(&thread->thread_id, NULL, thread_start, (void *)&thread);
printf("num: %i\n",thread->thread_num);
pthread_exit(NULL);
return 0;
}
But the value that print the main doesn't change (2).
And then I want to create an array of thread struct, but I don't know how exactly do that:
I guess it should be something like this:
int main(int argc, char *argv[])
{
int i;
struct thread pthread_data;
struct thread *thread[N-1] = &pthread_data; // I don't know how to manage this.
for(i=0; i<N; i++)
{
thread->thread_num=i;
pthread_create(&thread[i]->thread_id, NULL, thread_start, (void *)&thread[i]);
printf("num %i: %i\n",i,thread[i]->thread_num);
}
pthread_exit(NULL);
return 0;
}
Any thoughts?
I recommend you to read http://www.advancedlinuxprogramming.com/alp-folder/alp-ch04-threads.pdf
And here what you wanted:
#define N 5
typedef struct thread {
pthread_t thread_id;
int thread_num;
// int thread_sum;
} ThreadData;
void *thread_start(void *thread)
{
ThreadData *my_data = (ThreadData*)thread;
//there is no guarantee that prints will be in order
// we will use its initial thread->num ,cause it differs for each thread
//plus you will see how threads will behave
int order=my_data->thread_num;
printf("%i) before num T: %i\n",order, my_data->thread_num);
my_data->thread_num=4;
printf("%i) after assignment num T: %i\n",order ,my_data->thread_num);
return NULL;
}
int main(int argc, char *argv[])
{
int i;
ThreadData thread[N];
for(i=0; i<N; i++)
{
thread[i].thread_num=i;
pthread_create(&(thread[i].thread_id), NULL, thread_start, (void *)(thread+i));
}
//wait for all threads
for (i = 0; i < N; i++)
pthread_join(thread[i].thread_id, NULL);
//print results of each thread
for (i = 0; i < N; i++)
printf(" %i)thread: number %i\n",i,thread[i].thread_num);
return 0;
}
I can see multiple mistakes in your code.
First you have your pointers wrong. In the first example, it is enough to pass &pthread_data to pthread_create, &thread is the address of the thread pointer, so you are passing struct thread ** to your function instead of struct thread *. In the second example you should use (void *) thread[i]. &thread[i] is again struct thread **.
When you want each thread to write to its own thread data, then you should make an array of thread data, so that each thread has its own piece, else you will run into race conditions.
As others have already pointed out, you should call pthread_join before calling printf to ensure that the main thread will wait for all worker threads.
Also note that if you are calling pthread_join from other function that the one that spawned those threads, you have to ensure that the array of tread data will not go out of scope (in this case it would be probably better to use malloc or a global array).
You can't. As soon as main exits, which it does when you call pthread_exit, pthread_data ceases to exist, since it's local to the main function. So it can't be modified.
This is my code. It's very simple.
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *func(void *arg)
{
printf("ID=%d\n", *(int*)arg);
pthread_exit(NULL);
}
int main()
{
pthread_t pt[4];
int i;
for (i = 0; i < 4; i++)
{
int temp = i;
pthread_create(&pt[i], NULL, func, (void*)&temp);
}
sleep(1);
return 0;
}
I compiled it:
gcc p_test.c -lpthread
I ran it. It printed 2 2 3 3. I ran it again. It printed 2 3 3 2.
My problem is:
Why was 2 or 3 printed twice?
Why didn't it print 1 3 2 0 or any other results?
The major problem here is that you're taking the address of the local variable temp, and then using that pointer outside the scope of the variable - as soon as you exit one iteration of the loop, your pointer to temp becomes invalid and you must not dereference it.
You're passing a pointer to a temporary variable into the thread creation function and this temporary goes out of scope at the end of the loop block. It would seem to me that the temporary address is being reused by the compiler and so that when the threads are executing, they see the same address location.
If you do:
int *temp = malloc(sizeof(int));
*temp = i;
pthread_create(&pt[i], NULL, func, (void*)temp);
instead, you should see the results you expect.
In this case, the thread function needs to free the int after it is printed it to avoid a memory leak.
Also, it's better practice to pthread_join() the threads that you're waiting for rather than just sleep()ing.
because it prints temp, all threads shares the memory(why temp is "shared" is explained by TheJuice), so all threads "share" temp . Use a mutex or make temp a private variable.
Private Variables in Threads
Or you can use phtread_join like this:
int main()
{
pthread_t pt[4];
int i;
for (i =0 ; i < 4; i++)
{
pthread_create(&pt[i], NULL, func, (void*)&i);
pthread_join(pt[i],NULL);
}
//sleep(1);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *func(void* arg)
{
printf("ID=%d\n", (int)arg);
pthread_exit(NULL);
return 0;
}
int main()
{
pthread_t pt[4];
int i;
for (i =0 ; i < 4; i++)
{
pthread_create(&pt[i], NULL, func, (void*)i);
pthread_join(pt[i],NULL);
}
return 0;
}
I have this piece of code that is giving me trouble.
I know all the threads are reading the same struct. But I have no idea how to fix this.
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int a,b;
} s_param;
void *
threadfunc(void *parm)
{
s_param *param2 = parm;
printf("ID:%d and v:%d\n",param2->a,param2->b);
pthread_exit(NULL);
}
int main(int argc, char **argv)
{
pthread_t thread[3];
int rc=0,i;
void * status;
for(i=0; i<3 ; ++i){
s_param param;
param.b=10;
param.a=i;
rc = pthread_create(&thread[i], NULL, threadfunc, ¶m ); // !!!!
if(rc){
exit(1);
}
}
for(i=0; i<3 ; ++i){
pthread_join(thread[i],&status);
}
return 0;
}
output:
ID:2 and v:10
ID:2 and v:10
ID:2 and v:10
and what I need:
ID:0 and v:10
ID:1 and v:10
ID:2 and v:10
The scope of the sparam in the for loop is static within that loop. When you set .a and .b you are writing to the same struct over and over, and all three threads are getting a pointer to that same single struct.
Instead, you could create three separate instances of the struct by making an array of them like so..
int main(int argc, char **argv)
{
pthread_t thread[3];
s_param param[3];
int rc=0,i;
void * status;
for(i=0; i<3 ; ++i){
param[i].b=10;
param[i].a=i;
rc = pthread_create(&thread[i], NULL, threadfunc, ¶m[i] ); // !!!!
if(rc){
exit(1);
}
}
... etc
Should mention that creating the structs (and the threads) in an array like this is only feasible since you clearly do a join() with the main thread. If you didn't do that join, you would be advised to either statically allocate the structs outside of the main function, or malloc them from the heap, because as soon as the entry thread exits the main function, the stack frame containing the array will become invalid and will soon be overwritten in an unpredictable way.
param lives on the same place in the stack during the execution of your main function. Every time you set new values, they're wiping out the old values, and all the threadfuncs are looking at the same spot in memory. malloc the structs, or otherwise create them from different memory locations. (Also, using stack memory for cross-thread data structures is worrisome; as soon as the function you're setting them up in exits, the memory is invalid.)
param is a local variable. It goes out of scope at the end of the loop's braces. You need to malloc a new s_param with each thread.
Or better, define a struct containing both a pthread_t and an s_param and use that type for thread[3].
typedef struct {
int a,b;
pthread_t t;
} s_param;
int main(int argc, char **argv)
{
s_param thread[3]; // declare threads + params together
int rc=0,i;
void * status;
for(i=0; i<3 ; ++i){
s_param *param = &thread[i]; // no persistent data declared here
param->b=10;
param->a=i;
rc = pthread_create(&thread[i].t, NULL, threadfunc, &thread[i] ); // !!!!
if(rc){
exit(1);
}
}
…