简体   繁体   English

如何在C pthread中并行化线程

[英]How to parallelize threads in C pthreads

I have N threads and they have to do job on shared data. 我有N个线程,它们必须处理共享数据。

I am using following structure: 我正在使用以下结构:

int main(){
    pthread_create(..., func, ...);
}

void *func(void *id){
    lock;
    do_job;
    unlock;
}

My problem is that threads seem to work sequentially. 我的问题是线程似乎按顺序工作。 How to actually make them parallel? 如何使它们平行?

They're serialising because you're holding the lock across your entire operation. 之所以将它们序列化,是因为您在整个操作过程中都持有该锁。 To actually get parallelism you'd need to do something like: 要真正获得并行性,您需要执行以下操作:

void func(void *id) {
    lock;
    do something serialised with shared data;
    unlock;

    do something that can be parallelised safely;

    lock;
    do something else with shared data;
    unlock;
}

The trick (as it is in anything threaded or otherwise parallelised) is working out where you need to serialise in order to not break things. 技巧(就像在任何线程化或并行化的东西中一样)正在解决您需要序列化的地方,以免破坏事物。 This is not easy. 容易。

The sequence of which thread is scheduled to run depend on several things: 计划运行哪个线程的顺序取决于几件事:

  • Thread priority 线程优先级
  • Schedule policy 时间表政策
  • Task attribution. 任务归因。

    On single CPU , unless some thread will be blocked (for example because of waiting I/O), creating several threads will not make the program running fast. 在单个CPU上,除非将阻止某些线程(例如,由于等待I / O),否则创建多个线程将不会使程序快速运行。 Instead, it might make the program slower because of the the task switch overhead. 相反,由于任务切换的开销,它可能会使程序变慢。

And also notice the difference between concurrency and parallelism . 还要注意并发和并行之间的区别。

Hold the lock for as small an operation as possible. 握住锁以进行尽可能小的操作。 If you don't, then the threads' order of execution degenerates into a sequential task (thread N executes and locks the resource, now thread N must finish before any other threads can resume work, thread N finished and thread N+1 executes, assumes the lock, and so forth..). 如果不这样做,则线程的执行顺序会退化为顺序任务(线程N执行并锁定资源,现在线程N必须先完成,其他线程才能继续工作,线程N完成,线程N + 1执行,承担锁,依此类推..)。 Also try to interleave memory-I/O access (which I'm arbitrarily assuming is what the lock is protecting) with computation, to achieve some greater degree of parallelism. 还尝试将内存I / O访问(我随意假定是锁正在保护的内容)与计算进行交织,以实现更高程度的并行性。

尽可能使用读/写锁

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM