gpt4 book ai didi

c - Mutex 的最佳替代方案——执行时间更短

转载 作者:行者123 更新时间:2023-11-30 17:29:56 25 4
gpt4 key购买 nike

请参阅以下代码:

我有一些库文件,例如 libexample.so在我的代码中,我使用库中存在的一些函数 X(inputbuffer , outputbuffer)

/*
Assume for each thread there are corresponding input buffers and output buffers
example if there are 50 threads 50 input buffers and out buffers are available
i.e input buffers are unique to each other so as output buffers....
*/
void* threadFunX(void *num)
{
Mutex lock();
int ret = X(inputBuffer,outputbuffer,length);
if(ret)
{
//store the output buffer in afile
}
else
error occured.....
Mutex unlock();
pthread_exit(NULL);
}

int main()
{
pthread_t thread1[100];

for(i=0;i<100;i++){
p1 = pthread_create(&thread1[i],NULL,threadFunX,(void *)i);
if(p1)
printf("Error occurred while creating thread.....\n");
//pthread_join( thread1[i], NULL);
}
for(i=0;i<100;i++)
pthread_join( thread1[i], NULL);

}

我的问题:如果我们不使用互斥锁,我们的输出缓冲区就会损坏......因此我们正在使用互斥锁......除了互斥之外还有其他方法吗......我想高效地使用这个库函数......我的主要动机是我也想减少互斥方法所花费的运行时间......例如...如果我的互斥体代码运行时间为 0.2 秒...我想要更好的替代方法,它比线程并行编程的互斥体花费更少的时间...

提前致谢...

最佳答案

检查库函数X。您确定每次调用该函数时都会创建一个新的OutputBuffer吗?因为根据您的说法“没有互斥锁输出缓冲区正在损坏”,在我看来,只创建了一个输出缓冲区,并且它向每个线程返回相同的输出缓冲区。

关于c - Mutex 的最佳替代方案——执行时间更短,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25443081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com