简体   繁体   English

使用pthreads()创建和管理线程

[英]Creating and managing threads with pthreads()

I went thorough different pthread tutorials on the web. 我浏览了网络上不同的pthread教程。 here , here and here among others. 这里这里这里等等。 But there is a questions that is still left unanswered, and was wondering if anyone could clarify it. 但是有一个问题仍然没有答案,并且想知道是否有人可以澄清它。

Question: 题:

  • Suppose I want to print ababababa . 假设我要打印ababababa And suppose thread1 is printing a and thread2 is printing b . 并假设thread1正在打印athread2正在打印b This means that thread1 executes then hands over the control to thread2 . 这意味着thread1执行,然后将控制权thread2thread2 Then thread2 prints b and control is handed over back to thread1 , so on and so forth. 然后thread2打印b并将控制权移交给thread1 ,依此类推。 In such a scenario, is it possible to create two threads and call each one at a time inside a loop that executes a specific number of times(using thread ID or some builtin function?)? 在这种情况下,是否可以创建两个线程并在执行特定次数(使用线程ID或某些内置函数?)的循环内一次调用每个线程? Or do i have to create two threads each time using a loop? 还是我每次必须使用循环创建两个线程?

eg: should i do something like: 例如:我应该做类似的事情:

  create_thread1()
  create_thread2()
  for loop
      call thread1()
      call thread2

or should i do something like: 还是我应该做类似的事情:

  for loop
      create_thread1() to do something
      create_thread2() to do something

EDIT: I removed part of the details from questions, cause users thought that was the question. 编辑:我从问题中删除了部分细节,因为用户认为这是问题。

EDIT: code 编辑:代码

void *func(void *arg){
    int i;
    while(i<30){

        printf("%s\n",(char *)arg);
        i++;
    }
    return 0;
}


int main(int argc, char *argv[]){

    pthread_t thread1, thread2;
    int rt1, rt2;
    rt1 = pthread_create(&thread1, NULL, &func, "a");
    rt2 = pthread_create(&thread2, NULL, &func, "b");

    sleep(1);
    return;
}

Have a global variable sum and in Thread1 add 10 to sum 1000 times and in Thread2 subtract 5 from sum 1000 times. 有一个全局变量和在线程1加10 总结了1000次,在线程2减去5从总和 1000倍。 Run both the Threads and see the output. 运行两个线程并查看输出。 Race condition will occur. 比赛条件将会发生。 Peterson's algorithm is to avoid race condition. 彼得森的算法是避免竞争条件。 Here sum += 10 and sum -= 5 are the critical sections. 其中sum + = 10sum-= 5是关键部分。 Now implement Peterson's algorithm and see the output. 现在实现彼得森算法,并查看输出。

This is the best example to demonstrate the working of Peterson's algorithm. 这是演示彼得森算法工作的最佳示例。

Ok. 好。 So i found out that both my assumptions were wrong. 所以我发现我的两个假设都是错误的。 Cause I assumed that threads that are created will be executed serially. 原因我假设创建的线程将串行执行。 But when creating threads, the OS will execut the threads randomly and in parallel. 但是在创建线程时,操作系统将随机并行执行线程。 so I implemented it as below: 所以我实现了如下:

create_thread1(call function1)
create_thread2(call function2)

function1(){
  loop
}

function1(){
  loop
}

A partial answer 部分答案

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

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