user513164
user513164

Reputation: 1858

c multithreading process

I want to write a multi threaded program in c language. I use posix thread library.

I write the following code:

#include<stdio.h>
#include<pthread.h>

void *put (int *arg)
{
    int i;
    //int * p;
    // p=(int*)arg;
    for(i=0;i<5;i++)
    { 
        printf("\n%d",arg[i]);
    }
    pthread_exit(NULL);
}

int main()
{
    int a[5]={10,20,30,40,50};
    pthread_t s;
    pthread_create(&s,NULL,put,a);
    printf("what is this\n");
    return 0;
}

I just want my thread just show the items in the array. The program compiled with following warning:

tm.c:19: warning: passing argument 3 of ‘pthread_create’ from incompatible pointer type
/usr/include/pthread.h:227: note: expected ‘void * (*)(void *)’ but argument is of type ‘void * (*)(int *)’

When I run the program I got the out put of main thread but not the value stored in array.

Now can anyone tell me what I'm doing wrong? How to send the array as an argument in the thread function?

If I just changed the code little bit the compile time warning resolved the changed code is following:

#include<stdio.h>
#include<pthread.h>


void *put (void *arg)
{
    int i;
    int * p;
    p=(int*)arg;
    for(i=0;i<5;i++)
    { 
        printf("\n%d",p[i]);
    }
    pthread_exit(NULL);
}

int main()
{
    int a[5]={10,20,30,40,50};
    pthread_t s;
    pthread_create(&s,NULL,put,a);
    printf("what is this\n");
    return 0;
}

But the output does not change. Can any one tell me what i did wrong? What is the proper way to send array to a thread function (put in this case)?

Upvotes: 1

Views: 381

Answers (3)

shodanex
shodanex

Reputation: 15406

Try to wait for your thread to execute, add

pthread_join(s, NULL);

before your return 0;

Upvotes: 0

David Heffernan
David Heffernan

Reputation: 612794

First of all, you need to wait for the thread to finish before returning from main().

Another problem with this code is that the array a is allocated on the stack of the main() routine and is thus potentially invalid in the context of a different thread. You should heap allocate a with a call to malloc().

If you wait for the thread to finish in main() then a is probably valid since the stack frame for main() will still exist. However, any future refactorings are liable to cause you grief so please switch to using malloc().

Upvotes: 0

user2100815
user2100815

Reputation:

Your code creates the thread and then the process exits by reaching the end of main. You have to wait for the thread to have a chance to execute, by calling pthread_join, or sleeping for a bit.

Upvotes: 5

Related Questions