开发者

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 开发者_如何学Python*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)?


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.


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().


Try to wait for your thread to execute, add

pthread_join(s, NULL);

before your return 0;

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜