【发布时间】: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