Linux-C-Day6-线程

2023-02-26  本文已影响0人  国服最坑开发

1.子线程创建

//
// Created by gorey on 2023/02/27.
//
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#include <pthread.h>

pthread_t sub_tid;

void print_tds(const char *s) {
    pid_t pid;
    pthread_t tid;
    pid = getpid();
    tid = pthread_self();
    printf("%s pid: %u, tid: %u (0x%x)\n", s, (unsigned int) pid, (unsigned int) tid, (unsigned int) tid);
}

/**
 * 子线程处理内容
 */
void *thr_fn(void *arg) {
    print_tds(arg);
    return NULL;
}


int main(int argc, char *argv[]) {
    int err;
    err = pthread_create(&sub_tid, NULL, thr_fn, "new thread: "); // 创建子线程,通过函数传入子线程处理内容
    if (err != 0) {
        fprintf(stderr, "can't create thread: %s\n", strerror(err));
        exit(1);
    }
    printf("sub thread id: %u\n", sub_tid);
    print_tds("main thread:");

    sleep(1);

    return 0;
}

2.线程同步

//
// Created by gorey on 2023/02/27.
//
#include <stdlib.h>
#include <stdio.h>
#include <signal.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#include <fcntl.h>
#include <pthread.h>


void *thr_fn1(void *arg) {
    printf("thread 1 returning \n");
    sleep(3);
    return (void *) 1;
}

void *thr_fn2(void *arg) {
    printf("thread 2 returning \n");
    return (void *) (2 + (long) arg);
}

void *thr_fn3(void *arg) {
    while(1) {
        printf("thread 3 writing\n");
        sleep(1);
    }
}


/**
 * 线程三种退出方法
 * 1.子线程 return
 * 2.子线程调用 pthread_cancel 结束另一个同进程中的线程。分同步和异步两种场景考虑
 * 3.线程调用本线程的 pthread_exit
 */
int main(int argc, char *argv[]) {
    pthread_t tid;
    void *tret;

    pthread_create(&tid, NULL, thr_fn1, NULL);
    pthread_join(tid, &tret); // 主线程 等待子线程结束。 正常结束时,tret 保存的是 子线程方法返回值。
    printf("thread 1 exit code %ld\n", (long) tret);

    pthread_create(&tid, NULL, thr_fn2, (void *) 100); // 第4个参数为 子线程函数的参数
    pthread_join(tid, &tret);
    printf("thread 2 exit code %ld\n", (long) tret);

    pthread_create(&tid, NULL, thr_fn3, NULL);
    sleep(3);
    pthread_cancel(tid); // 让子线程结束
    pthread_join(tid, &tret);  //  此时再去同步等待子线程, tret的结果是:PTHREAD_CANCELED (-1)
    printf("thread 3 exit code %ld\n", (long) tret);

    return 0;
}

输出:

thread 1 returning 
thread 1 exit code 1
thread 2 returning 
thread 2 exit code 102
thread 3 writing
thread 3 writing
thread 3 writing
thread 3 writing
thread 3 exit code 1
上一篇 下一篇

猜你喜欢

热点阅读