两个线程实现同步代码示例

#include 
#include 

int count = 0;
pthread_mutex_t mutex;

void* task(void* arg)
{
    for (int i = 0; i < 1000; i++) {
        pthread_mutex_lock(&mutex);
        count++;
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

int main() 
{
    pthread_t tid1, tid2;
    pthread_mutex_init(&mutex, NULL);

    pthread_create(&tid1, NULL, task, NULL);
    pthread_create(&tid2, NULL, task, NULL);

    pthread_join(tid1, NULL);
    pthread_join(tid2, NULL);

    pthread_mutex_destroy(&mutex);

    printf("Count: %d\n", count);

    return 0;
}

你可能感兴趣的:(java,开发语言)