本文介绍了订购两个线程的执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 我想要写两个线程,首先会读取从控制台的字符串,而第二个会输出它的字符数。 要做到这一点,我必须设置执行的线程,先读,写第二的顺序。此外,我想一个线程在同时执行。我怎样才能做到这一点? 的#include&LT;&stdio.h中GT;#包括LT&;&stdlib.h中GT;#包括LT&;&pthreads.h中GT;无效* printCharacterNumber(无效* PTR);无效* readMessage(无效* PTR);诠释的main(){ 的pthread_t线程1,线程; INT iret1,iret2; iret1 = pthread_create的(安培;线程1,NULL printMessage,NULL); iret2 = pthread_create的(安培;线程2,NULL printCharacterNumber,NULL); 在pthread_join(线程1,NULL); 在pthread_join(线程2,NULL); 返回0;}无效* readMessage(无效* PTR){ 字符*消息; FSCAN(%S,&安培;消息);}无效* printCharacterNumber(无效* PTR){ 的printf(%S,消息); //我要加计数时,它会工作} 解决方案 genine(pthread的)的最大的兴趣线程是使并行执行(几个最核心的笔记本电脑和台式机有获利了结)...看了一些 pthread的教程 ... 您可能需要使用的障碍。了解更多关于 pthread_barrier_wait &安培; pthread_barrier_init 如果要序列一些反,你可以使用(最近C11编译器,如 GCC 4.9 )一些原子内建的,或者更通常是互斥,看到的调用pthread_mutex_init &安培; 的pthread_mutex_lock等....: 静态pthread_mutex_t MTX =调用pthread_mutex_init; 静态长计数器; 无效increment_serialized_counter(无效){ 调用pthread_mutex_lock(安培; MTX); 反++; pthread_mutex_unclock(安培; MTX); } 长get_serialized_counter(无效){ 长R = 0; 调用pthread_mutex_lock(安培; MTX); R =计数器; pthread_mutex_unclock(安培; MTX); 返回ř; } 您也许应该使用互斥为您的消息变量,如果它是静态的!I wanna write two threads, first will read a string from the console, and the second will output the number of characters in it.To do so, I have to set the order of executing the threads, reading first, writing second.Also I want one thread to execute at the time.How can I do this?#include <stdio.h>#include <stdlib.h>#include <pthread.h>void *printCharacterNumber(void *ptr);void *readMessage(void *ptr);int main(){ pthread_t thread1, thread2; int iret1, iret2; iret1 = pthread_create(&thread1, NULL, printMessage, NULL); iret2 = pthread_create(&thread2, NULL, printCharacterNumber, NULL); pthread_join(thread1, NULL); pthread_join(thread2, NULL); return 0;}void *readMessage(void *ptr){ char *message; fscan("%s", &message);}void *printCharacterNumber(void *ptr){ printf("%s", message); // I'll add counting when it will work} 解决方案 The biggest interest of genine (pthread) threads is to enable parallel execution (taking profit of the several cores most laptops and desktops have)...Read some pthread tutorial ...You may want to use barriers. Read more about pthread_barrier_wait & pthread_barrier_initIf you want to serialize some counter, you could use (with recent C11 compilers, e.g. GCC 4.9) some atomic builtins, or more usually a mutex, see pthread_mutex_init & pthread_mutex_lock etc....: static pthread_mutex_t mtx = PTHREAD_MUTEX_INIT; static long counter; void increment_serialized_counter (void) { pthread_mutex_lock(&mtx); counter++; pthread_mutex_unclock(&mtx); } long get_serialized_counter (void) { long r = 0; pthread_mutex_lock(&mtx); r = counter; pthread_mutex_unclock(&mtx); return r; }You probably should use a mutex for your message variable, if it was static! 这篇关于订购两个线程的执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-01 17:03