ÆÊÎöLinuxÀú³ÌΪʲô»á½øÈë˯Ãßģʽ
ÆÊÎöLinuxÀú³ÌΪʲô»á½øÈë˯Ãßģʽ£¬ÐèÒªÏêϸ´úÂëʾÀý
ÔÚLinuxϵͳÖУ¬Àú³Ì»áÓÉÓÚ¶àÖÖÔµ¹ÊÔÓɽøÈë˯Ãßģʽ¡£Ë¯Ãßģʽ°üÀ¨ÆÚ´ý×ÊÔ´¡¢ÆÚ´ýÐźźÍÆÚ´ýÊÂÎñµÈÇéÐΡ£±¾ÎĽ«´ÓÕ⼸¸ö·½ÃæÏêϸÆÊÎöLinuxÀú³ÌΪʲô»á½øÈë˯Ãßģʽ£¬²¢Í¨¹ýÏêϸµÄ´úÂëʾÀýÀ´ËµÃ÷¡£
ÆÚ´ý×ÊÔ´
Àú³ÌÔÚÖ´ÐÐÀú³ÌÖУ¬¿ÉÄÜÐèÒª»á¼ûһЩ¹²Ïí×ÊÔ´£¬ÈçÎļþ¡¢ÍøÂçÅþÁ¬¡¢ÄÚ´æµÈ¡£µ±Ä³Ò»×ÊÔ´±»ÆäËûÀú³ÌÕ¼ÓûòÕß±»Ëø׼ʱ£¬Ä¿½ñÀú³Ì¾Í»á½øÈë˯Ãßģʽ£¬ÆÚ´ý×ÊÔ´µÄÊÍ·Å»ò½âËø¡£
ÏÂÃæÊÇÒ»¸öʾÀý´úÂ룬չʾÁËÒ»¸öÏß³ÌÆÚ´ý»ñÈ¡Ò»¸öËø×ÊÔ´µÄÀú³Ì£º
#include <stdio.h> #include <pthread.h> pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int shared_resource = 0; void* thread_function(void* arg) { pthread_mutex_lock(&mutex); shared_resource++; pthread_mutex_unlock(&mutex); return NULL; } int main() { pthread_t thread; pthread_create(&thread, NULL, thread_function, NULL); pthread_mutex_lock(&mutex); while (shared_resource == 0) { pthread_mutex_unlock(&mutex); sched_yield(); // ×Ô¶¯ÈóöCPU£¬×èֹæÆÚ´ý pthread_mutex_lock(&mutex); } pthread_mutex_unlock(&mutex); pthread_join(thread, NULL); return 0; }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬Ö÷Ïß³ÌÆÚ´ý×ÓÏ̻߳ñÈ¡Ëø×ÊÔ´ºó²Å»ª¼ÌÐøÖ´ÐУ¬µ±×ÓÏ̻߳ñÈ¡Ëø×ÊÔ´ºó£¬Ö÷Ï߳̾ͻáÍ˳ö˯Ãß״̬¡£
ÆÚ´ýÐźÅ
Àú³Ì¿ÉÒÔͨ¹ýÐźÅÓëÄںˡ¢ÆäËûÀú³Ì¾ÙÐÐͨѶ¡£µ±Àú³ÌÆÚ´ýÐźŵִïʱ£¬»á½øÈë˯Ãß״̬¡£¿ÉÒÔͨ¹ýsigwait()»òÕßÐźŴ¦Àíº¯ÊýµÈ·½·¨À´´¦ÀíÐźš£
ÏÂÃæÊÇÒ»¸öʹÓÃsigwait()º¯ÊýÆÚ´ýÐźŵÄʾÀý´úÂ룺
#include <stdio.h> #include <signal.h> int main() { sigset_t set; int sig_no; sigemptyset(&set); sigaddset(&set, SIGUSR1); sigprocmask(SIG_BLOCK, &set, NULL); sigwait(&set, &sig_no); printf("Received signal SIGUSR1 "); return 0; }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬Àú³ÌÛÕ±ÕSIGUSR1Ðźţ¬µ±ÎüÊÕµ½¸ÃÐźÅʱ£¬¾Í»áÍ˳ö˯Ãß״̬£¬²¢Ö´ÐÐÏìÓ¦²Ù×÷¡£
ÆÚ´ýÊÂÎñ
Àú³ÌÓÐʱ¼äÐèÒªÆÚ´ýijЩÊÂÎñµÄ±¬·¢£¬ºÃ±È׼ʱÆ÷³¬Ê±¡¢IOÊÂÎñÍ£µ±µÈ¡£Àú³Ì»áÓÉÓÚÆÚ´ýÊÂÎñ¶ø½øÈë˯Ãß״̬£¬Ö±µ½ÊÂÎñ±¬·¢²¢ÇÒ½ÐÐÑÀú³Ì¡£
ÏÂÃæÊÇÒ»¸öʹÓÃIO¶à·¸´ÓÃÆÚ´ýÊÂÎñµÄʾÀý´úÂ룺
#include <stdio.h> #include <sys/select.h> int main() { fd_set rfds; struct timeval tv; int retval; FD_ZERO(&rfds); FD_SET(0, &rfds); tv.tv_sec = 5; tv.tv_usec = 0; retval = select(1, &rfds, NULL, NULL, &tv); if (retval == -1) { perror("select()"); } else if (retval) { printf("Data is available now. "); } else { printf("No data within five seconds. "); } return 0; }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÃæµÄ´úÂëÖУ¬Àú³ÌʹÓÃselect()º¯ÊýÆÚ´ý±ê×¼ÊäÈëÊÇ·ñÓÐÊý¾Ý¿É¶Á£¬µ±Êý¾Ý¿É¶Á»òÕßÆÚ´ý³¬Ê±£¬Àú³Ì¾Í»á±»½ÐÐÑ¡£
×ÛÉÏËùÊö£¬LinuxÀú³Ì»áÓÉÓÚÆÚ´ý×ÊÔ´¡¢ÆÚ´ýÐźźÍÆÚ´ýÊÂÎñµÈÔµ¹ÊÔÓɽøÈë˯Ãßģʽ¡£Í¨¹ýÏêϸµÄ´úÂëʾÀý£¬¿ÉÒÔ¸üºÃµØÃ÷È·Àú³ÌµÄ˯ÃßÐÐΪ¡£
ÒÔÉϾÍÊÇÆÊÎöLinuxÀú³ÌΪʲô»á½øÈë˯ÃßģʽµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡