#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h> //needed for Mac Linux
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; // Declares Mutex Lock Globally
void* print_i(void *ptr)
{
pthread_mutex_lock(&mutex); //ensures whole function gets executed without interleaving
printf("1: I am \n");
sleep(1); //program to pause for 1 sec
printf("in i\n");
return NULL; //needed b/c function does not return anything
pthread_mutex_unlock(&mutex); //releases function to continue rest of program
}
void* print_j(void *ptr)
{
pthread_mutex_lock(&mutex); //ensures whole function gets executed without interleaving
printf("2: I am \n");
sleep(1); //program to pause for 1 sec
printf("in j\n");
return NULL; //needed b/c function does not return anything
pthread_mutex_unlock(&mutex); //releases function to continue rest of program
}
int main()
{
pthread_t t1,t2;
int rc1 = pthread_create(&t1, NULL, print_i, NULL);
int rc2 = pthread_create(&t2, NULL, print_j, NULL);
pthread_join(t1, NULL); //allows functions to iterate completely(T1,T2,Main,T1,T2,Main..)
pthread_join(t2, NULL); //allows functions to iterate completely(T1,T2,Main,T1,T2,Main..)
exit(0);
}
我们应该得到以下结果:
1: I am/n
in I/n
2: I am/n
in j/n
我的输出实际上是:
1: I am
in i
在我的实际输出之后,我似乎被“卡在”程序中了。例如,向上箭头生成“^[[A”。任何帮助我们找出为什么没有达到预期结果的帮助将不胜感激。我使用的是 M1 MacBook Pro。
最佳答案
return语句之后的下一个语句没有获得控制权
return NULL; //needed b/c function does not return anything
pthread_mutex_unlock(&mutex);
因此互斥体未解锁。
关于c - 为什么第二个函数没有运行和/或产生输出? (Linux 中的 C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75837500/