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;
}