请问下版主,我在linux中创建多个线程,为什么跑一次就跑完了?我要求两个线程死循环轮流直行,请问下怎么实现,代码的整体架构如下:
#include <pthread.h>
#include <stdio.h> /* stand input and output... */
#include <stdlib.h> /* stand lib */
#include <unistd.h> /* UNIX stand function */
#include <sys/types.h> /**/
#include <sys/stat.h> /**/
#include <fcntl.h> /* file controle */
#include <termios.h> /*PPSIX terminal controle */
#include <errno.h> /* error */
#include <string.h>
#include <netinet/in.h>
#include <sys/wait.h>
#include <sys/socket.h>
#include <sys/time.h>
pthread_t thread[2];
pthread_mutex_t mut;
void thread1()
{
pthread_mutex_lock(&mut);//////////////////////////////BY ZF
/******************TCP/IP***********************/
tcp协议栈的初始化.........
while(1)
{
printf ("thread1 : I'm thread 1\n");
while(1)
{
printf("Server is runing........\r\n");
pthread_mutex_unlock(&mut);//////////////////////BY ZF
sleep(2);
}
}
void thread2()
{
int fd;
int length;
/*****************test buf***************/
unsigned char rcv[10];
printf("thread2 : I'm thread 2\n");
pthread_mutex_lock(&mut);////////////////////////////BY ZF
fd = open("/dev/ttyS0", O_RDWR); // read and write
if(fd == -1)
{
printf("Can't open ttyS0!\n");
exit(0);
}
set_speed(fd, B9600); // set baud 9600
if (set_data_format(fd, 8, 1, 'N')== -1)
{
printf("Data format Error!\n");
exit(1);
}
while(1)
{
length = read(fd, rcv, 10);
printData(rcv,sizeof(rcv));
write(fd, rcv, length);
close(fd);
pthread_mutex_unlock(&mut);/////////////////BY ZF
sleep(3);
}
}
void thread_create(void)
{
memset(&thread, 0, sizeof(thread)); //comment1
/*创建线程*/
pthread_create(&thread[0], NULL, (void*)&thread1, NULL);
pthread_create(&thread[1], NULL,(void*)& thread2, NULL);
}
void thread_wait(void)
{
/*等待线程结束*/
if(thread[0] !=0) {
pthread_join(thread[0],NULL);
printf("线程1已经结束\n");
}
if(thread[1] !=0) {
pthread_join(thread[1],NULL);
printf("线程2已经结束\n");
}
}
/************* main() ********************/
int main()
{
pthread_mutex_init(&mut,NULL);
thread_create();
thread_wait();
}
麻烦哪位高手帮我分析下?