c - 这些线程中的每一个是否都会等到互斥体解锁后才能执行某项功能?

标签 c multithreading mutex

下面是我的系统类中的互斥锁程序。它为输入字符串中的每个字母创建一个新线程,然后将所有其他字母转换为大写。 我的问题是,c 中的线程在执行函数之前实际上“等待”互斥锁解锁吗?或者如果方法被锁定,他们只是使操作失败?

#include <stdio.h>
#include <string.h>
#include <pthread.h>

#define SIZE 50

char sentence[2000];
int  ind = 0;

pthread_mutex_t count_mutex;

void
increment_ind()
{
    ind = ind + 1;    
}

char convertUppercase(char lower)
{
    //Converts lowercase un uppercase
    if ((lower > 96) && (lower < 123))
        return (lower - 32);
    else
        return lower;
}

void printChar()
{
    //prints the converted sentence
    printf("The new sentence is [%d]: \t%c\n", ind, sentence[ind]);
    increment_ind();
}

void *convertMessage(void *ptr)
{
    pthread_mutex_lock(&count_mutex);   

    // Function that each threads initiates its execution
    char aux;

    if (ind % 2)
        sentence[ind] = convertUppercase(sentence[ind]);

    printChar();
    pthread_mutex_unlock(&count_mutex);
    return 0;
}

int main()
{
    int i;
    char buffer[SIZE];
    char *p;
    pthread_t ts[SIZE]; // define up to 50 threads

    printf("Please enter a phrase (less than 50 characters): ");

    if (fgets(buffer, sizeof(buffer), stdin) != NULL_
        if ((p = strchr(buffer, '\n')) != NULL)
            *p = '\0';

    strcpy(sentence, buffer);
    printf("The original sentence is: \t %s\n", sentence);

    // create one thread for each character on the input word
    for(i = 0; i < strlen(buffer) + 1; ++i)
        pthread_create(&ts[i], NULL, convertMessage, NULL);

    // we wait until all threads finish execution
    for(i = 0; i < strlen(buffer); i++)
        pthread_join(ts[i], NULL);

    printf("\n");

    return 0;
}

最佳答案

是的,线程通常会等待互斥锁变得可用,但不是你的。我认为您问这个问题的原因是您的线程都忽略了互斥体。它们的原因是在 main() 中你忘记调用:

pthread_mutex_init(&count_mutex, NULL);

更糟糕的是,您忘记检查以下内容的返回值:

pthread_mutex_lock(&count_mutex);

由于未初始化的互斥体,它会输出错误代码 22!

下面是我对您的代码进行的修改,以解决上述问题,修复其他错误(您启动的线程比您加入的线程多,等等),以及一些样式调整:

#include <stdio.h>
#include <string.h>
#include <pthread.h>

#define SIZE 50

char sentence[2000];
int ind = 0;

pthread_mutex_t count_mutex;

void increment_ind()
{
    ind = ind + 1;
}

char convertUppercase(char character)
{
    // Converts lowercase to uppercase
    if (character >= 'a' && character <= 'z')
    {
        character -= ' ';
    }

    return character;
}

void printSentence()
{
    // prints the converted sentence
    printf("The new sentence is [%d]: %s\n", ind, sentence);
}

void *convertMessage(void *pointer)
{
    if (pthread_mutex_lock(&count_mutex) == 0)
    {
        // Function that each threads initiates its execution
        if (ind % 2 == 1)
        {
            sentence[ind] = convertUppercase(sentence[ind]);
        }

        printSentence();

        increment_ind();

        (void) pthread_mutex_unlock(&count_mutex);
    }
    else
    {
        /* handle the error! */
    }

    return NULL;
}

int main()
{
    char *p, buffer[SIZE];
    pthread_t threads[SIZE]; // define up to 50 threads

    (void) pthread_mutex_init(&count_mutex, NULL);

    printf("Please enter a phrase (less than 50 characters): ");

    if (fgets(buffer, sizeof(buffer), stdin) == NULL)
    {
        /* print an error message to stderr */
        return 1;
    }

    if ((p = strchr(buffer, '\n')) != NULL)
    {
        *p = '\0';
    }

    (void) strcpy(sentence, buffer); // copy local string to global string

    printf("The original sentence is: %s\n", sentence);

    // create one thread for each character in the input string
    for (int i = 0; i < strlen(buffer); i++)
    {
        (void) pthread_create(&threads[i], NULL, convertMessage, NULL);
    }

    // we wait until all threads finish execution
    for (int i = 0; i < strlen(buffer); i++)
    {
        (void) pthread_join(threads[i], NULL);
    }

    printf("\n");

    return 0;
}

关于c - 这些线程中的每一个是否都会等到互斥体解锁后才能执行某项功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40137998/

相关文章:

c - 如何避免文件系统的缓冲机制

c++ - 使用 pthreads 的线程安全队列

c++ - 多线程类中互斥体可能出现段错误

c++ - 标准 :mutex'es as members of objects that will go into containers?

c - 互斥锁线程

c - LabWindows 中的实时数据过滤?

c - 函数中的scanf重复输入请求两次

c - 使用属性 warn_unused_result [-Wunused-result] 声明

multithreading - 什么是竞争条件?

c# - 带秒表的线程安全方法