MST
星途 面试题库

面试题:C语言线程池的同步与通信

在基于C语言的Linux线程池模型中,如何处理线程间的同步与通信问题,以确保任务的正确执行和资源的合理利用?请举例说明可能用到的同步机制及其在代码中的具体实现方式。
25.7万 热度难度
编程语言C

知识考点

AI 面试

面试题答案

一键面试

在基于C语言的Linux线程池模型中,处理线程间的同步与通信问题可采用以下同步机制:

互斥锁(Mutex)

  1. 作用:用于保护共享资源,确保同一时间只有一个线程能够访问该资源。
  2. 代码示例
#include <pthread.h>
#include <stdio.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int shared_variable = 0;

void* thread_function(void* arg) {
    // 加锁
    pthread_mutex_lock(&mutex);
    shared_variable++;
    printf("Thread incremented shared variable: %d\n", shared_variable);
    // 解锁
    pthread_mutex_unlock(&mutex);
    return NULL;
}

int main() {
    pthread_t thread;
    pthread_create(&thread, NULL, thread_function, NULL);
    pthread_join(thread, NULL);
    pthread_mutex_destroy(&mutex);
    return 0;
}

条件变量(Condition Variable)

  1. 作用:用于线程间的同步,一个线程等待某个条件满足,另一个线程在条件满足时通知等待的线程。
  2. 代码示例
#include <pthread.h>
#include <stdio.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int ready = 0;

void* waiting_thread(void* arg) {
    pthread_mutex_lock(&mutex);
    while (!ready) {
        printf("Waiting thread is waiting...\n");
        pthread_cond_wait(&cond, &mutex);
    }
    printf("Waiting thread got notified.\n");
    pthread_mutex_unlock(&mutex);
    return NULL;
}

void* notifying_thread(void* arg) {
    pthread_mutex_lock(&mutex);
    ready = 1;
    printf("Notifying thread is signaling...\n");
    pthread_cond_signal(&cond);
    pthread_mutex_unlock(&mutex);
    return NULL;
}

int main() {
    pthread_t t1, t2;
    pthread_create(&t1, NULL, waiting_thread, NULL);
    pthread_create(&t2, NULL, notifying_thread, NULL);
    pthread_join(t1, NULL);
    pthread_join(t2, NULL);
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&cond);
    return 0;
}

信号量(Semaphore)

  1. 作用:用于控制对共享资源的访问数量,允许多个线程同时访问共享资源,但限制访问的线程数量。
  2. 代码示例
#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>

sem_t sem;
int shared_resource = 0;

void* thread_function(void* arg) {
    sem_wait(&sem);
    shared_resource++;
    printf("Thread incremented shared resource: %d\n", shared_resource);
    sem_post(&sem);
    return NULL;
}

int main() {
    sem_init(&sem, 0, 1);
    pthread_t thread;
    pthread_create(&thread, NULL, thread_function, NULL);
    pthread_join(thread, NULL);
    sem_destroy(&sem);
    return 0;
}

在实际的线程池模型中,可结合这些同步机制。例如,任务队列作为共享资源,可用互斥锁保护。当任务队列中有新任务时,可通过条件变量通知空闲线程。若线程池允许一定数量线程同时处理任务,信号量可用于控制并发线程数量。