Create threads and create multi-threaded

Using threads (compare with the process memory)
pthread_self (): Gets the thread ID / getpid (): Get Process ID
pthread_create: create a thread / fork (): create a process
(Note: where the function is a thread of execution, the pointer function address)

    ***int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                     void *(*start_routine) (void *), void *arg);***
        参数一:pthread_t 类型地址
        参数二:线程属性
        参数三:线程函数地址
        参数四:线程函数的形参

Create a single thread

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

void *pthread_func(void * arg)
{
        printf("IN thread: tid = %ld, pid=%d\n",pthread_self(),getpid());
}
          
int main()
{         
        pthread_t tid;
        
        int ret = pthread_create( &tid , NULL , pthread_func,NULL);
        if(ret != 0)
        {
                printf("pthread_creat error\n");//perror打印的是系统调用,strerror(int mun)是库函数
                exit(1);
        }

        printf("IN main pthread: tid = %ld , pid =%d\n",pthread_self(),getpid());
        sleep(1);
    
        
        return 0 ;
}

Create multiple threads

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

void *pthread_func(void  * arg)
{
        int i = (int)arg;
        sleep(i);
        printf("%dth IN thread: tid = %lu, pid=%u\n",i+1,pthread_self(),getpid());

        return NULL;
}

int main()
{
        pthread_t tid;
        int i =0,ret;

        for(i =0; i< 5 ; ++i)
        {
                ret = pthread_create( &tid , NULL , pthread_func,(void *)i);//此处i用值传递,用&i传递会出错
                if(ret != 0)
                {
                        printf("pthread_creat error");
                        exit(1);
                }
        }

        sleep(i);
        return 0 ;
}

Published 38 original articles · won praise 13 · views 4314

Guess you like

Origin blog.csdn.net/YanWenCheng_/article/details/104046595