pthread创建单线程和多线程实例,并且多线程循环执行

下面代码示例是使用C语言编写的pthread多线程执行,注意使用 编译指令 gcc -o test main.c -lpthread

#include 
#include 
#include 

// 编译指令 gcc -o test main.c -lpthread

// 线程函数-执行一次退出
void *print_hello(void *arg) {
    printf("Hello from thread %ld \n", (long)arg);
    pthread_exit(NULL);
}

// 线程函数-循环执行
void *print3_hello(void *arg) 
{
    while(1)
    {
        printf("Hello-3 from thread %ld \n", (long)arg);
        sleep(1);
    }
}

// 线程函数-循环执行
void *print4_hello(void *arg) 
{
    while(1)
    {
        printf("Hello-4 from thread %ld \n", (long)arg);
        sleep(1);
    }
}

int main() {
    const int num_threads = 5;
    pthread_t threads[num_threads];
    int rc;
    long t;

    for (t = 0; t < num_threads; t++) {
        printf("In main: creating thread %ld \n", t);
        if (t < 3)
            rc = pthread_create(&threads[t], NULL, print_hello, (void *)t);
        else if (t==3)
            rc = pthread_create(&threads[t], NULL, print3_hello, (void *)t);
        else if (t==4)
            rc = pthread_create(&threads[t], NULL, print4_hello, (void *)t);

        if (rc) {
            printf("ERROR; return code from pthread_create() is %d \n", rc);
            exit(-1);
        }
    }

    /* Wait for all threads to finish. */
    // for (t = 0; t < num_threads; t++) {
    //     pthread_join(threads[t], NULL);
    // }
    while(1)
    {
        printf("while 1 \n");
        // pthread_join(threads[3], NULL);
        // pthread_join(threads[4], NULL);
        sleep(5);
    }

    printf("All threads have finished \n");
    pthread_exit(NULL);
}

下面是执行日志

root@ubuntu:/home/du/share# ./test 
In main: creating thread 0 
In main: creating thread 1 
In main: creating thread 2 
In main: creating thread 3 
In main: creating thread 4 
while 1 
Hello from thread 1 			// 这个线程执行一次就退出
Hello-3 from thread 3 
Hello from thread 2 
Hello-4 from thread 4 
Hello from thread 0 
Hello-3 from thread 3 
Hello-4 from thread 4 
Hello-3 from thread 3 
Hello-4 from thread 4 
Hello-3 from thread 3 
Hello-4 from thread 4 
Hello-3 from thread 3 
Hello-4 from thread 4 
while 1 								// 执行一次主进程
Hello-3 from thread 3 		// 会执行多次子线程
Hello-4 from thread 4 
Hello-3 from thread 3 
Hello-4 from thread 4 
Hello-3 from thread 3 
Hello-4 from thread 4 
Hello-3 from thread 3 
Hello-4 from thread 4 

你可能感兴趣的:(linux与虚拟机,linux)