我必须使用 c 中的线程程序从服务器读取一些文件(日志)。程序应该保持同步,一方面这个子线程应该正在执行,同时主线程应该通知它的子线程的时间。
因此,在示例程序中,我试图在子线程中运行日志记录功能,同时父进程/父线程/主线程将以秒为单位的打印时间已经通过运行日志记录。
PS:我的问题是如果我将使用 pthread_join() 那么第一个 logreading 函数将执行,它实际上是由于无限循环而阻塞线程。而且我无法在主要功能中获得控制流。无论如何,我想同时执行两者而不会互相打扰。我在 Java 中使用线程和同步方法做了类似的事情。但是在 CI 中对多线程编程的了解并不多
目前我没有使用锁,因为我不想要停止/恢复条件,我唯一的要求是两个函数保持启动,同时运行而不相互交互。谢谢您的帮助。
void process(FILE *FP, int sockfd);
int create_ma_header(char*, int, int, int, int);
void* t_main(void*);
int i;
int main(int argc, char** argv)
{
void* arg;
void* t_result;
if (argc != 2)
{
printf("usage: tcpcli <IPaddress>");
exit(0);
}
arg = (void*) argv[1];
pthread_t t;
pthread_attr_t t_attr;
pthread_attr_init(&t_attr);
printf("before calling pthread_create getpid: %d getpthread_self %u tid:%u\n",
getpid(), pthread_self(), syscall(SYS_gettid));
pthread_create(&t, &t_attr, t_main, (void*) argv[1]); //loging tread
/* if(pthread_join(t,&t_result) != 0)
{
printf("Thread not joined \n");
exit(1);
}
*/
printf("Thread joined and status is Logs are getting printed what else you want to do .... \n");
while (1)
{
printf(
"Running time of log reading displayed from main thread: %d seconds",
i++);
slep(1);
}
pthread_exit(0);
}
void* loging_thread(void* arg)
{
char* server_ip;
server_ip = (char*) arg;
int sockfd;
struct sockaddr_in servaddr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_port = htons(SERV_PORT);
inet_pton(AF_INET, server_ip, &servaddr.sin_addr);
printf(
"in loging_thread log has been redirected to log_read.dat getpid: %d getpthread_self %u tid:%u\n",
getpid(), pthread_self(), syscall(SYS_gettid));
connect(sockfd, (struct sockaddr *) &servaddr, sizeof(servaddr));
process(stdin, sockfd); /* do it all */
pthread_exit(0);
}
void process(FILE *fp, int sockfd)
{
FILE* log_f;
int fd;
fd = open("log_read.dat", O_CREAT | O_WRONLY, 0644);
char sendline[MAXLINE];
char reply[MAXLINE], string2[MAXLINE], *body;
char *p1, *p2, *p3;
create_ma_header(reply, 999, 999, VERSION, 999);
write(sockfd, reply, sizeof(reply));
while (1)
{
char header[SDNS_MA_HEADERSZ];
read(sockfd, body, size);
write(fd, body, size);
}
}
int create_ma_header(char * reply, int type, int size, int version, int lic)
{
sprintf(reply, "%4d%c%10d%c%4d%c%4d", type, SD_PIPE, size, SD_PIPE, version,
SD_PIPE, lic);
if (strlen(reply) != 26 - 1)
{
return 0;
}
reply[strlen(reply)] = SD_PIPE;
return 1;
}
char * get_ma_header(char *curr_p, int *type_p, int *size_p, int *version_p,
int *lic_p)
{
*type_p = (int) strtol(curr_p, NULL, 10);
curr_p += 5;
*size_p = (int) strtol(curr_p, NULL, 10);
curr_p += 11;
*version_p = (int) strtol(curr_p, NULL, 10);
curr_p += 5;
*lic_p = (int) strtol(curr_p, NULL, 10);
curr_p += 5;
return curr_p;
}