Linux中的进程和线程都是操作系统进行资源分配和调度的基本单位,但它们之间存在一些关键的区别和紧密的联系。
#include <stdio.h>
#include <unistd.h>
int main() {
pid_t pid = fork();
if (pid == 0) {
printf("I am the child process\n");
} else if (pid > 0) {
printf("I am the parent process\n");
} else {
perror("fork");
}
return 0;
}
#include <stdio.h>
#include <pthread.h>
void* thread_function(void* arg) {
printf("I am a thread\n");
return NULL;
}
int main() {
pthread_t thread;
if (pthread_create(&thread, NULL, thread_function, NULL) != 0) {
perror("pthread_create");
return 1;
}
pthread_join(thread, NULL);
printf("Thread finished\n");
return 0;
}
问题:线程间同步困难,容易出现竞态条件。 解决方法:使用互斥锁(mutex)、信号量(semaphore)等同步机制来保护共享资源。
#include <stdio.h>
#include <pthread.h>
int shared_data = 0;
pthread_mutex_t mutex;
void* thread_function(void* arg) {
pthread_mutex_lock(&mutex);
shared_data++;
pthread_mutex_unlock(&mutex);
return NULL;
}
int main() {
pthread_t threads[10];
pthread_mutex_init(&mutex, NULL);
for (int i = 0; i < 10; ++i) {
pthread_create(&threads[i], NULL, thread_function, NULL);
}
for (int i = 0; i < 10; ++i) {
pthread_join(threads[i], NULL);
}
printf("Shared data: %d\n", shared_data);
pthread_mutex_destroy(&mutex);
return 0;
}
通过上述代码,可以有效地保护共享数据shared_data
,避免竞态条件。
领取专属 10元无门槛券
手把手带您无忧上云