Linux多线程

linux 系统多线程编程

1. 基本概念

概念说明
线程 ID每个线程都有一个唯一的 id,通常是个长整型类。
线程属性线程的属性,如调度策略和优先级,可以通过线程属性对象来设定。
线程栈每个线程都有属于自己的栈控件,存储局部变量和函数调用的上下文。

2. 主要函数

函数说明
pthread_create()创建一个新的线程。
pthread_join()等待一个线程结束
pthread_detach()分离一个线程,使其自动结束,不必等待pyhread_join()
pthread_self()返回当前线程的 id
pthread_equal()判断两个线程是否相等
pthread_exit()退出当前线程

3. 代码示例

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

void* print_numbers(void* arg) {   // 线程回调函数
    long tid = (long)arg;  // 使用参数需要强制转换
    int i;
    for (i = 1; i <= 10; i++) {
        if (tid == 0 && i % 2 == 0) { // Even numbers
            printf("Thread %ld: %d\n", tid, i);
        } else if (tid == 1 && i % 2 != 0) { // Odd numbers
            printf("Thread %ld: %d\n", tid, i);
        }
    }
    pthread_exit(NULL);
}

int main() {
    pthread_t threads[2];
    int rc;

    // Create threads
    rc = pthread_create(&threads[0], NULL, print_numbers, (void *)0);
    if (rc) {
        printf("Error creating thread 0\n");
        return -1;
    }

    rc = pthread_create(&threads[1], NULL, print_numbers, (void *)1);
    if (rc) {
        printf("Error creating thread 1\n");
        return -1;
    }

    // Wait for both threads to finish
    pthread_join(threads[0], NULL);
    pthread_join(threads[1], NULL);

    printf("Main thread exiting.\n");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值