【问题标题】:how slow is mutex synchronization than no synchronization in 2 threads互斥同步比 2 个线程中不同步有多慢
【发布时间】:2020-06-07 01:57:28
【问题描述】:

我有两个线程需要在不同的内核中运行。当我在代码中不提供同步时,执行代码中的线程仅需约 0.6 秒(对于 N=100000000 的迭代)。当我使用互斥同步运行相同的代码时,线程到线程的时间约为 3 秒。我不确定这是否应该显示。应该这么慢吗?或者我在我的代码中犯了一个错误。

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
#include <time.h>
#include <sched.h>


int x=0;
long long i;
long long count=0;
pthread_mutex_t mutex;


double getsecs(void)
{
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return tv.tv_sec + tv.tv_usec / 1.0e6;
}


void* changetoone(void *arg)
        { 

  pthread_mutex_lock(&mutex);

         for (i=0; i<10000000; i++){

            count2=i;
            while(x!=1)


            { count= count+1;
                x=1;

              //printf("%d", x);


            }
            pthread_mutex_unlock(&mutex);

         }
         return NULL;

        }


void* changetozero(void *arg){
        pthread_mutex_lock(&mutex);//we can set one or more bits here, each one representing a single CPU

 for (i=0; i<10000000; i++){
            while(x!=0)
            {count= count+1;
             x=0;


          printf("%d", x);


             }
          pthread_mutex_unlock(&mutex);   
        } 

        return 0;           
       } 


int main()
{


    double t1 = getsecs();

    pthread_t thread1;

    pthread_create(&thread1, NULL, changetoone, &x);

    pthread_t thread2;
    pthread_create(&thread2, NULL, changetozero, &x);    

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);

    double t2 = getsecs();


    printf("elapsed seconds: %f, %f  uS/iteration\n", t2-t1,1000000*(t2-t1)/100000000);
   printf("%lld\n", count);

}

【问题讨论】:

    标签: multithreading synchronization mutex latency


    【解决方案1】:

    好吧,老实说,它真的不重要它有多慢。要么你需要同步,要么你不需要。

    在需要时不使用它可能会导致错误的结果。您希望代码慢还是代码不正确?

    话虽如此,我看到您的线程在 1000 万次迭代循环的整个持续时间内都锁定了互斥锁。这实际上与按顺序调用这两个函数相同。如果您想要真正的并发,锁定和解锁操作将在循环内部,类似于(伪代码):

    do 10,000,000 times:
        lock mutex
        do operation
        unlock mutex
    

    但请记住,线程仅在争用相对时才有用。如果两个线程在 99% 的时间里都需要一个锁(就像您的代码中的情况一样,即使 在循环内移动锁),如果任何。

    可能甚至会看到性能下降,因为线程大多仍是互斥的,但添加了互斥体以减慢速度。

    【讨论】:

    • 将 N 增加到 100000000 为互斥量提供 26 秒。我仍然不确定这是否会很慢。我的目标是查看不同同步方法的时间。
    • @ZZI。没关系,但我不确定您是否已阅读我的答案。您应该尝试同步 within 循环,看看有什么效果。但是您需要记住,如果线程将大部分时间都花在锁上,那么多线程不会给您带来很多性能提升。
    • @ZZI - 换句话说:如果您想获得有意义的测量结果,您需要了解您正在测量的内容,并帮助您解决实际(或假设)问题。跨度>
    猜你喜欢
    • 2014-05-02
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多