c - 尝试了解 pthread 在 C 中的工作原理

标签 c multithreading pthreads pthread-join pthread-exit

我正在尝试在 C 中使用 pthread 来比较两个字符串。这个想法是看看完整的字符串 2 是否在字符串 1 中(例如,如果 string1 = lkajdsglstring2 = jd 那么我将有一个匹配)。我不明白的是 pthread 一般是如何工作的。在这里,我正在创建我的 pthreads,假设 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 调用在 main 中是如何准确工作的。然而,这是我为该函数提供的伪代码,此处 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
}

最佳答案

If the string is 12 characters long and I only have 3 threads how does the system know to keep analyzing the string with the 3 threads until all 12 characters have been examined?

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

However, what I don't understand is how to use pthread_join.

pthread_join 只是等待线程退出。仅此而已。

关于c - 尝试了解 pthread 在 C 中的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43577881/

相关文章:

c - GCC 程序未定义对函数的引用(多个文件夹)

c++ - 定义一个指针来引用相同的变量名引用?

linux - 在 Linux 上使用信号与 POSIX 线程

Java线程自发唤醒

linux - 我需要在多线程读取调用中保护 fd 吗?

c - fifo 循环队列中的 pthread_cond_wait 死锁

c - 为什么我不能在函数外分配(由 malloc 动态分配)变量?

python - numba 函数什么时候编译?

执行线程时更改C线程参数

c - C 中的多线程错误段错误