嗨朋友们,我在这里遇到线程同步问题。我对线程很陌生,这就是为什么要向你们寻求帮助。在我的代码中,我必须从串口读取数据,然后将数据发送到 UDP 端口。为此,我有两个额外的线程。在第一个线程中,我正在无限循环中读取数据,而在第二个线程中,我正在做一些处理然后发送。
问题是我在第二个线程中没有得到 buff1[0] 的值,其整数值为== 1,这意味着我很少得到值 ==1。但在第一个线程中,我不断获得 buff1[0] 的值。
我怀疑这是因为我没有使用互斥锁。如果有必要,我想知道如何在我的代码中使用互斥锁。请指导我改进我的源代码
下面是我的代码
#include <stdio.h> /* Standard input/output definitions */
#include <string.h> /* String function definitions */
#include <unistd.h> /* UNIX standard function definitions */
#include <fcntl.h> /* File control definitions */
#include <errno.h> /* Error number definitions */
#include <termios.h> /* POSIX terminal control definitions */
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "CapSerial.h"
#include <stdlib.h>
#include<time.h>
//this portion added for thread
#include <pthread.h>
#include "lcd_api.h"
struct in_addr localInterface;
struct sockaddr_in groupSock;
void *serial1Thread();
void *serial2Thread();
char buff1[1024];
int sd,min,sec,hr;
int datalen;
char finalbuf[30];
static int serial1_status=0,serial2_status=0;
char serial1[16],sendbuff[16];
int fd_lcd ,min,sec,hr,ret,secsend,minsend;
struct sockaddr_in servaddr,cliaddr,cliaddr1;
char serial2[16],serial1[16];
char sec_buf[3],min_buf[3],hr_buf[3];
char sec_send[3],min_send[3],hr_send[3];
char sec_buf[3],min_buf[3],hr_buf[3];
int sockfd,n,i,sockfd1;
int fd1,fd2,i,ret1,ret2,ret3;
int main(int argc, char **argv)
{
pthread_t thread1,thread2;
sockfd = socket(AF_INET,SOCK_DGRAM,0);
bzero(&cliaddr,sizeof(cliaddr));
cliaddr.sin_family = AF_INET;
cliaddr.sin_addr.s_addr = inet_addr("10.111.4.100");
cliaddr.sin_port = htons(1229);
ret1=pthread_create(&thread1,NULL,serial1Thread,NULL);
ret3=pthread_create(&thread2,NULL,serial2Thread,NULL);
pthread_join(thread1,NULL);
pthread_join(thread2,NULL);
return 0;
}
void *serial1Thread()
{
fd1 = open("/dev/ttyS1", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd1 == -1)
{
perror("open_port: Unable to open /dev/ttyS1 - ");
return 0;
}
else
{
fcntl(fd1, F_SETFL, 0);
}
initport(fd1, 9600);
printf("baud=%d\n", getbaud(fd1));
while(1)
{
// Reading Data in infinite while loop
if(readport(fd1, buff1))
{
printf("Read Error happened \n");
exit(0);
}
else
{
printf("\n The value of buff1[0]=%d",buff[0]);
}
}
}
void *serial2Thread()
{
while(1)
{
printf("\n The value of buff1[0]=%d",buff[0]);
sendto(sockfd,sendbuff,14,0,(struct sockaddr *)&cliaddr,sizeof(cliaddr));
}
}
问题是 buff1[0] 的值是 SOH(标题开始),其整数值 ==1 每次都不能在第二个线程中使用。