multithreading(pthread) compete code

#include #include #include int global; int i = 30; int j = 30; int k = 30; pthread_mutex_t mutex; void* child1(void* arg) { while(k--) { pthread_mutex_lock(&mutex); global++; printf("from child1\n"); printf("%d\n",global); pthread_mutex_unlock(&mutex); } } void* child2(void* arg) { while(j--) { pthread_mutex_lock(&mutex); global++; printf("from child1\n"); printf("%d\n",global); pthread_mutex_unlock(&mutex); } } int main() { pthread_t tid1, tid2; pthread_mutex_init(&mutex, NULL); pthread_create(&tid1, NULL, child1, NULL); pthread_create(&tid2, NULL, child2, NULL); while(i--) { pthread_mutex_lock(&mutex); global++; printf("from main\n"); printf("%d\n",global); pthread_mutex_unlock(&mutex); } return 0; } I'm new to pthread and multithreading, the result of this code is **from main xx** and **child1** appeared rarely, the three threads never appear together, what's the problem?
It isn't necessarily the case that printf() flushes output with a newline, and I have no idea how the underlying implementation of printf() works here, but before you go about jumping through the harder hoops, I'd recommend adding a fflush(stdout) to ensure that at each iteration for each thread the output buffer has been fully flushed in between critical sections and has no chance of being overwritten through some magical asynchronous happenstance. If the easy check doesn't pan out, then worry about other issues.

以上就是multithreading(pthread) compete code的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » CSS3 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏