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

时间:2014-11-13 22:12:20

标签: c multithreading pthreads

我在网上浏览了不同的pthread教程。 hereherehere等。但有一些问题仍然没有得到解答,并且想知道是否有人可以澄清它。

问题:

  • 假设我要打印a b a b a b a b a。假设thread1正在打印athread2正在打印b。这意味着thread1执行然后将控件交给thread2。然后thread2打印b并将控件移交给thread1,依此类推。在这种情况下,是否有可能创建两个线程并在执行特定次数的循环内一次调用每个线程(使用线程ID或某些内置函数?)?或者每次使用循环时我是否必须创建两个线程?

e.g: 我应该这样做:

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

或者我应该这样做:

  for loop
      create_thread1() to do something
      create_thread2() to do something
编辑:我从问题中删除了部分细节,导致用户认为这是个问题。

编辑:代码

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;
}

2 个答案:

答案 0 :(得分:0)

拥有全局变量 sum ,并在Thread1中将10添加到 sum 1000次,并在Thread2中减去5来自 总和 1000次。运行两个线程并查看输出。将出现比赛条件。彼得森的算法是避免竞争条件。 这里 sum + = 10 sum - = 5 是关键部分。现在实现Peterson的算法并查看输出。

这是展示彼得森算法工作的最好例子。

答案 1 :(得分:0)

确定。所以我发现我的假设都是错误的。因为我假设创建的线程将被串行执行。但是在创建线程时,操作系统将随机并行地执行线程。所以我按如下方式实现了它:

create_thread1(call function1)
create_thread2(call function2)

function1(){
  loop
}

function1(){
  loop
}

A partial answer