Mutex的最佳替代品 - 这需要更少的执行时间

时间:2014-08-22 08:51:45

标签: c pthreads

请参阅以下代码:

我有一些像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);

}

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

提前致谢...

1 个答案:

答案 0 :(得分:0)

检查库功能 X 。您确定每次调用该函数时都会创建一个新的 OutputBuffer 。因为按照你的说法“没有互斥输出缓冲区被破坏”,在我看来,只创建了一个输出缓冲区,并且它会向每个线程返回相同的内容。

相关问题