linux 线程 是进程

#include <stdio.h>
#include <pthread.h>
void* thread( void *arg )
{
    printf( "This is a thread and arg = %d.\n", *(int*)arg);
    *(int*)arg = 0;
    return arg;
}
int main( int argc, char *argv[] )
{
    pthread_t th;
    int ret;
    int arg = 10;
    int *thread_ret = NULL;



    ret = pthread_create( &th, NULL, thread, &arg );
    if( ret != 0 ){
        printf( "Create thread error!\n");
        return -1;
    }
    printf( "This is the main process.\n" );
    pthread_join( th, (void**)&thread_ret );// 天天 这个可能后于thread函数的发生
    printf( "thread_ret = %d.\n", *thread_ret );
    return 0;
}

将这段代码保存为thread.c文件,可以执行下面的命令来生成可执行文件:

$ gcc thread.c -o thread -lpthread

这段代码的执行结果可能是这样:

$ ./thread
This is the main process.
This is a thread and arg = 10.
thread_ret = 0.

ref

https://www.cnblogs.com/jiu0821/p/6707912.html

发布了216 篇原创文章 · 获赞 33 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/paulkg12/article/details/103085937