Linux中的进程和线程都是操作系统进行资源分配和调度的基本单位,但它们之间存在一些关键的区别。
进程:
线程:
进程:
线程:
创建进程:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
void child_process() {
printf("Child process\n");
}
int main() {
pid_t pid = fork();
if (pid == 0) { // 子进程
child_process();
} else if (pid > 0) { // 父进程
printf("Parent process\n");
} else {
perror("fork");
exit(EXIT_FAILURE);
}
return 0;
}
创建线程:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void* thread_function(void* arg) {
printf("Thread running\n");
return NULL;
}
int main() {
pthread_t thread;
int result = pthread_create(&thread, NULL, thread_function, NULL);
if (result != 0) {
perror("pthread_create");
exit(EXIT_FAILURE);
}
pthread_join(thread, NULL);
printf("Thread finished\n");
return 0;
}
问题:线程间数据竞争。 原因:多个线程同时访问和修改共享数据,导致数据不一致。 解决方法:
示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int shared_data = 0;
pthread_mutex_t mutex;
void* thread_function(void* arg) {
for (int i = 0; i < 100000; ++i) {
pthread_mutex_lock(&mutex);
shared_data++;
pthread_mutex_unlock(&mutex);
}
return NULL;
}
int main() {
pthread_t thread1, thread2;
pthread_mutex_init(&mutex, NULL);
pthread_create(&thread1, NULL, thread_function, NULL);
pthread_create(&thread2, NULL, thread_function, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
printf("Shared data: %d\n", shared_data);
pthread_mutex_destroy(&mutex);
return 0;
}
通过上述方法可以有效避免数据竞争问题,确保线程安全。
领取专属 10元无门槛券
手把手带您无忧上云