用于C语言中的线程程序的sched_yield

时间:2017-02-27 03:15:22

标签: c multithreading

我正在尝试使用3个线程来打印以VOWEL,CONSONANTS和OTHER开头的单词。这是我的计划:

int main(int argc, char** argv)
{
int i,j,n_thread;

pthread_t threads[3];

digit=0;vowels=0;consonants=0,pos=1;


pthread_create(&threads[0],NULL,check_Vower(argc,argv),NULL);
pthread_create(&threads[1],NULL,check_Consonant(argc, argv),NULL);
pthread_create(&threads[2],NULL,check_Other(argc, argv),NULL);


pthread_join(threads[0],NULL);
pthread_join(threads[1],NULL);
pthread_join(threads[2],NULL);

printf("\nVowels = %d",vowels);
printf("\nConsonants = %d",consonants);
printf("\nDigits = %d",digit);
return 0;    
}

void *check_Vower(int argc, char** argv)
{

char first;
printf("Thread Vower\n");
int i;

//while(argv[pos] != NULL)
for(i = 1; i < argc; i++)
{
    printf("arg pos %s\n", argv[pos]);
    first = argv[pos][0];
    //if(isalpha(first)){
        if( (toupper(first)=='A') || (toupper(first)=='E') ||     (toupper(first)=='I') || (toupper(first)=='O') || (toupper(first)=='U'))
        {
            //pthread_mutex_lock(&lock1);
            printf("VOWEL: %s\n", argv[pos]);
            vowels++;
            pos++;
            // sched_yield();
            //pthread_mutex_unlock(&lock1);
        }
    //} 

    sched_yield();  
    printf("dkm\n");
}

pthread_exit(NULL);
}

void *check_Consonant(int argc, char** argv)
{
printf("Thread consonants\n");
char first;
int i;

//while(argv[pos] != NULL)
for(i = 1; i < argc; i++)
{
    first = argv[pos][0];

    //if(isalpha(first)){
        if( (toupper(first) !='A') && (toupper(first)!='E') && (toupper(first)!='I') && (toupper(first)=='O') && (toupper(first)!='U'))
        {
            //pthread_mutex_lock(&lock1);
            printf("VOWEL: %s\n", argv[pos]);
            vowels++;
            pos++;
            //sched_yield();
            //pthread_mutex_unlock(&lock1);
        }
    //}

    else
        sched_yield();
    printf("sche_yield fails \n");
}

pthread_exit(NULL);
}

void *check_Other(int argc, char** argv)
{
printf("Thread Other\n");
int temp;
char first;
temp=toupper(first)-65;

int i;

//while(argv[pos] != NULL)
for(i = 1; i < argc; i++)
{
    first = argv[pos][0];

    if(!isalpha(first))
    {
        if(temp>-17 && temp<-7) 
        {
            //pthread_mutex_lock(&lock1);
            printf("OTHER: %s\n", argv[pos]);
            digit++;
            pos++;
            //sched_yield();
            //pthread_mutex_unlock(&lock1);
        } 
    }else
        sched_yield();
}

pthread_exit(NULL);
}

sched_yield一旦无法检测到该线程的字,就会产生对下一个线程的控制权,但它只是通过for循环重复,DID不会放弃对CPU的控制,程序在执行后就会停止。

在执行线程时我做错了什么?

1 个答案:

答案 0 :(得分:1)

这与yield和调用带有错误参数的pthread_create的所有事情无关。

您是否完全忽略了有关指针类型的所有编译器警告?

你在pthread_create期间调用你的线程函数。然后线程尝试将返回值作为线程函数执行。