Linux线程控制是指在Linux操作系统中对线程进行创建、管理和同步的一系列操作。线程是进程中的一个执行单元,是CPU调度和分派的基本单位,比进程更小,被包含在进程之中,是实现进程中多个并发执行流的手段。
pthread_create
函数创建新线程。pthread_exit
函数主动退出,或者通过pthread_cancel
函数被其他线程取消。pthread_exit
或pthread_cancel
。以下是一个简单的Linux线程创建和同步的示例:
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
pthread_mutex_t lock;
void* thread_func(void* arg) {
int id = *(int*)arg;
pthread_mutex_lock(&lock);
printf("Thread %d has acquired the lock
", id);
// 模拟一些工作
sleep(1);
printf("Thread %d is releasing the lock
", id);
pthread_mutex_unlock(&lock);
pthread_exit(NULL);
}
int main() {
pthread_t threads[5];
int thread_ids[5];
int i;
if (pthread_mutex_init(&lock, NULL) != 0) {
printf("Mutex init failed
");
return 1;
}
for (i = 0; i < 5; i++) {
thread_ids[i] = i;
if (pthread_create(&threads[i], NULL, thread_func, &thread_ids[i]) != 0) {
printf("Thread creation failed
");
return 1;
}
}
for (i = 0; i < 5; i++) {
pthread_join(threads[i], NULL);
}
pthread_mutex_destroy(&lock);
return 0;
}
在这个示例中,我们创建了5个线程,每个线程在访问共享资源(这里是打印操作)前都会获取一个互斥锁,确保同一时间只有一个线程能够执行打印操作,从而避免竞态条件。
没有搜到相关的文章