【问题标题】:Trying to understand how pthread works in C试图了解 pthread 在 C 中的工作原理
【发布时间】:2017-09-20 12:46:41
【问题描述】:

我正在尝试在 C 中使用 pthread 来比较两个字符串。我们的想法是查看完整的字符串 2 是否在字符串 1 中(例如,如果 string1 = lkajdsglstring2 = jd 那么我会有一个匹配项)。我不明白的是 pthread 如何以一般方式工作。在这里,我正在创建我的 pthread,假设 NUM_THREADS=3,那么我应该有 3 个线程,线程 [0]、线程 [1] 和线程 [2]。每个都将调用 Pthrd_Substring 函数。字符串将从文件中读取并在函数中进行分析。但是,我不明白的是如何使用pthread_join。如果字符串有 12 个字符长并且我只有 3 个线程,那么系统如何知道要继续使用 3 个线程分析字符串,直到检查完所有 12 个字符? (该函数查看字符串 1 中的每个字母,并将其与字符串 2 中的第一个字母进行比较,然后确定是否存在完整的字符串 2。)

int main(int argc, char *argv[])
{
    pthread_t threads[NUM_THREADS];
    int count, rc;
    long t;

    for(t=0;t<NUM_THREADS;t++){
     printf("In main: creating thread %ld\n", t);
     rc = pthread_create(&threads[t], NULL, Pthrd_Substring, (void *)t);
     if (rc){
       printf("ERROR; return code from pthread_create() is %d\n", rc);
       exit(-1);
       }
     }

    printf("The number of substrings is: %d\n", count);
    return 1;
}

我可以使用类似的东西:

pthread_join(threads0, NULL);
 partial_sum += t.partial_count;
pthread_join(threads1, NULL);
 partial_sum += t.partial_count;
pthread_join(threads2, NULL);
 partial_sum += t.partial_count;

并且在函数中有一个全局总计?但是,这会以某种方式检查字符串中的每个字母吗?


我犹豫是否要包含这部分,因为我没有完全解决它,因为我不明白 pthread 调用在主程序中是如何工作的。然而,这是我的函数的伪代码,这里n1string1 的字符串长度,n2string2 的长度:

void *Pthrd_Substring(void *thrdptr)
{
    int i,j,k;
    int count;
    int total = 0;

    for (i = thrdptr; i <= (n1-n2); i++){       
        count=0;
        for(j = i,k = 0; k < n2; j++,k++){  /*search for the next string of size of n2*/  
            if (*(s1+j)!=*(s2+k)){
                break;
            }
            else
                count++;
            if(count==n2)    
                total++;        /*find a substring in this step*/                          
        }
    }
    partial_count = total
}

【问题讨论】:

  • 请显示Pthrd_Substring。事实上,请务必提供minimal reproducible example
  • 我希望提供所需的信息。代码不“完整”,因为我还没有解决这一问题。
  • 这几乎是最糟糕的练习。我见过的多线程。使用多个线程进行琐碎大小的字符串搜索不仅非常不合适且效率低下,而且尝试以您描述的方式管理搜索是噩梦。
  • 如果您要这样做,请计算数组中的 [线程数] 起点,大小大致相等,并让 thre 线程仅在它们自己的部分中查找开始字符。不要让工作线程读取文件 - 将填充读入数组并将其加载到分配的结构中,连同每个线程的开始/长度,并将结构地址传递给 pthread_create()。将结果放入结构中并使用 pthread_exit() '返回' 结构。 pthread_join() 并累积结果后释放。
  • .. 或者更好的是,使用线程池,但鉴于任务的“热核弹头破解”性质,只需使用更简单的方法并获得一些分数。

标签: c multithreading pthreads pthread-join pthread-exit


【解决方案1】:

如果字符串有 12 个字符长,而我只有 3 个线程,系统如何知道要继续使用 3 个线程分析字符串,直到检查完所有 12 个字符?

系统不知道这一点——就像非线程编程一样。如果您想分析每个字符,那么您需要编写程序来分析每个字符。

但是,我不明白的是如何使用 pthread_join。

pthread_join 只是等待线程退出。就是这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    相关资源
    最近更新 更多