线程

来源:互联网 发布:公安大数据平台有哪些 编辑:程序博客网 时间:2024/06/07 16:18

gcc编译线程,要加-lpthread,gcc thread_struct.c -lpthread -o thread_struct

makefile文件的格式

cc=gccall: thread_id.c,thread_exit.cthread_id : gcc thread_id.c -lpthread -o thread_idthread_exit: $(cc) thread_exit.c -lpthread -o thread_exitclean: rm *.o;rm thread*

创建线程

#include <stdio.h>#

线程和进程公用一个pid号

#include <stdio.h>#include <pthread.h>#include <unistd.h> /*getpid()*/void *create(void *arg){    printf("New thread .... \n");    printf("This thread's id is %u  \n", (unsigned int)pthread_self());    printf("The process pid is %d  \n",getpid());    return (void *)0;}int main(int argc,char *argv[]){    pthread_t tid;    int error;    printf("Main thread is starting ... \n");    error = pthread_create(&tid, NULL, create, NULL);    if(error)    {        printf("thread is not created ... \n");        return -1;    }    printf("The main process's pid is %d  \n",getpid());    sleep(1);    return 0;}

运行结果如下:

Main thread is starting ... The main process's pid is 9057  New thread .... This thread's id is 3076262720  The process pid is 9057  

线程的三种返回方式

#include <stdio.h>#include <pthread.h>#include <unistd.h>void *create(void *arg){    printf("new thread is created ... \n");    //三种结果    return (void *)8;    //pthread_exit((void *)9);    //exit(0);}int main(int argc,char *argv[]){    pthread_t tid;    int error;    void *temp;    error = pthread_create(&tid, NULL, create, NULL);    printf("main thread!\n");    if( error )    {        printf("thread is not created ... \n");        return -1;    }    error = pthread_join(tid, &temp);    if( error )    {        printf("thread is not exit ... \n");        return -2;    }    printf("thread is exit code %d \n", (int )temp);    return 0;}

三种结果为

main thread!new thread is created ... thread is exit code 8 main thread!new thread is created ... thread is exit code 9 main thread!new thread is created ... 

exit(0)貌似是进程的命令,所以不会返回0

原创粉丝点击