c多线程过程

use*_*164 1 c multithreading

我想用c语言编写一个多线程程序.我使用posix线程库.

我写下面的代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

我只想让我的线程只显示数组中的项目.该程序编译时带有以下警告:

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 *)’
Run Code Online (Sandbox Code Playgroud)

当我运行程序时,我获得了主线程的输出,但没有存储在数组中的值.

现在谁能告诉我我做错了什么?如何在线程函数中将数组作为参数发送?

如果我只是稍微更改了代码,则编译时警告已解决,更改后的代码如下:

#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;
}
Run Code Online (Sandbox Code Playgroud)

但输出不会改变.谁能告诉我我做错了什么?将数组发送到线程函数的正确方法是什么(在这种情况下放置)?

小智 5

您的代码创建了该线程,然后通过到达结束退出该进程main.你必须等待线程有机会执行,通过调用pthread_join或休眠一下.