Linux C并发编程是指在Linux环境下使用C语言进行多任务或多线程编程的技术。这种编程方式允许程序在同一时间段内执行多个任务,从而提高程序的执行效率和响应速度。
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_THREADS 5
void* print_hello(void* thread_id) {
long tid = (long)thread_id;
printf("Hello World! Thread ID, %ld
", tid);
pthread_exit(NULL);
}
int main() {
pthread_t threads[NUM_THREADS];
int rc;
long t;
for(t = 0; t < NUM_THREADS; t++) {
printf("In main: creating thread %ld
", t);
rc = pthread_create(&threads[t], NULL, print_hello, (void*)t);
if (rc) {
printf("ERROR: return code from pthread_create() is %d
", rc);
exit(-1);
}
}
for(t = 0; t < NUM_THREADS; t++) {
pthread_join(threads[t], NULL);
}
pthread_exit(NULL);
}
在这个示例中,我们创建了5个线程,每个线程打印一条消息。pthread_create
函数用于创建线程,pthread_join
函数用于等待线程结束。
并发编程是一个复杂的领域,需要深入理解操作系统原理和同步机制。在实际开发中,还需要注意线程安全、资源管理和性能优化等问题。
领取专属 10元无门槛券
手把手带您无忧上云