美文网首页
线程同步

线程同步

作者: wjundong | 来源:发表于2019-12-23 09:51 被阅读0次

线程同步被定义为确保两个或多个并发进程或线程不会同时执行某个称为临界区的特定程序段的机制。

使用同步技术控制进程对临界区的访问。
当一个线程开始执行临界区(程序的序列化段)时,另一个线程应该等待,直到第一线程完成。

如果未应用适当的同步技术,则可能会导致竞争条件,其中变量的值可能是不可预测的,并且根据进程或线程的上下文切换的定时而变化。

线程同步问题

研究同步问题的示例代码:

#include <pthread.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 

pthread_t tid[2]; 
int counter; 

void* trythis(void* arg) 
{ 
    unsigned long i = 0; 
    counter += 1; 
    printf("\n Job %d has started\n", counter); 

    for (i = 0; i < (0xFFFFFFFF); i++) 
        ; 
    printf("\n Job %d has finished\n", counter); 

    return NULL; 
} 

int main(void) 
{ 
    int i = 0; 
    int error; 

    while (i < 2) { 
        error = pthread_create(&(tid[i]), NULL, &trythis, NULL); 
        if (error != 0) 
            printf("\nThread can't be created : [%s]", strerror(error)); 
        i++; 
    } 

    pthread_join(tid[0], NULL); 
    pthread_join(tid[1], NULL); 

    return 0; 
} 

在这个例子中,创建了两个线程(Job),并且在这些线程的start函数中,维护了一个计数器来获取关于启动的作业数量和完成时间的日志。

利用线程锁

#include <pthread.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <unistd.h> 

pthread_t tid[2]; 
int counter; 
pthread_mutex_t lock; 

void* trythis(void* arg) 
{ 
    printf("check\n");
    pthread_mutex_lock(&lock); 
    printf("ok\n");
    unsigned long i = 0; 
    counter += 1; 
    printf("\n Job %d has started\n", counter); 

    for (i = 0; i < (0xFFFFFFFF); i++) 
        ; 

    printf("\n Job %d has finished\n", counter); 

    pthread_mutex_unlock(&lock); 

    return NULL; 
}

int main(void) 
{ 
    int i = 0; 
    int error; 

    if (pthread_mutex_init(&lock, NULL) != 0) { 
        printf("\n mutex init has failed\n"); 
        return 1; 
    } 

    while (i < 2) { 
        error = pthread_create(&(tid[i]), NULL, &trythis, NULL); 
        if (error != 0) 
            printf("\nThread can't be created :[%s]", 
                strerror(error)); 
        i++; 
    }

    pthread_join(tid[0], NULL); 
    pthread_join(tid[1], NULL); 
    pthread_mutex_destroy(&lock); 

    return 0; 
} 

相关文章

网友评论

      本文标题:线程同步

      本文链接:https://www.haomeiwen.com/subject/bffznctx.html