pthread_mutex_lock 100%cpu?

码:

local void* s_accept_connections(tmpsock) void* tmpsock; { int32_t newfd; int32_t tmp; SOCKADDR_IN newsockaddr; pthread_t id; Connection* newconn; const char *s; char **splited; int i; StringVec *p; StringVec* next; Socket* sock; tmp = sizeof(newsockaddr); p = NULL; next = NULL; sock = (Socket *)tmpsock; if (!sock) return 0; while (true){ newfd = accept(sock->fd,(SOCKADDR *)&newsockaddr,&tmp); if (newfd fd = newfd; newconn->addr = newsockaddr; s = (const char *)inet_ntoa(newsockaddr.sin_addr); p = split_string(s,"."); if (p != NULL){ splited = (char **)MyMalloc(sizeof(*splited) + 12); i = 0; for (; p != NULL; p = next){ if (p && p->next){ next = p->next; }else{ break; } splited[i] = p->value; i++; } newconn->ip = swap_uint32_t((uint32_t)(atoi(splited[0])) + (atoi(splited[1]) << 8) + (atoi(splited[2]) << 16) + (atoi(splited[3]) <ip = 0; } newconn->closed = false; newconn->state = 0; newconn->state |= S_NEED_LOGIN; pthread_mutex_init(&g_ping_mutex,NULL); pthread_cond_init(&g_ping_cond,NULL); pthread_create(&id,NULL,s_ping_thread,(void *)newconn); a_conn(&sock->conn,newconn); #ifndef NDEBUG _("Accepting connection...\n"); #endif if (sock->has_callback){ sock->func(newconn); #ifndef NDEBUG _("Accepted connection\n"); #endif } } } return 0; } void start_accept(sock,join) Socket* sock; bool join; { pthread_t id; pthread_attr_t attr; if (!sock) return; if (!sock->conn){ sock->conn = (Connection *)MyMalloc(sizeof(*sock->conn)); if (!sock->conn) return; } set_nonblocking(sock->fd); set_nonblocking(sock->conn->fd); pthread_attr_init(&attr); pthread_mutex_init(&g_socket_mutex,NULL); if (join){ pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_JOINABLE); }else{ pthread_attr_setdetachstate(&attr,PTHREAD_CREATE_DETACHED); } pthread_create(&id,&attr,s_accept_connections,sock); if (join){ pthread_join(id,NULL); pthread_attr_destroy(&attr); pthread_mutex_destroy(&g_socket_mutex); } } 

它只是提供100%的CPU,任何想法? 如果需要更多代码,生病

是什么让你相信pthread_mutex_lock()负责CPU的使用?

使用调试器找出发生的情况。 我的猜测是你的套接字有问题,使你的accept()调用无阻塞。

检查返回值/消息(如果您正在运行linux,则使用perror() )。

编辑:

您需要知道循环调试器的哪一段代码可以帮助您找到它。

你有一个while(true)循环很可能负责enless循环和100%CPU使用率。 它应该没问题,因为你有一个accept()调用(这里: newfd = accept(sock->fd,(SOCKADDR *)&newsockaddr,&tmp); )应该停止线程/进程直到下一个客户端连接。 但是如果您的套接字未正确初始化,则accept()可能会在不等待的情况下返回错误。