ÔÚLinuxÉÏʹÓÃOpenMP¾ÙÐв¢Ðбà³ÌµÄÉèÖÃÒªÁì
ÔÚlinuxÉÏʹÓÃopenmp¾ÙÐв¢Ðбà³ÌµÄÉèÖÃÒªÁì
OpenMP£¨Open Multi-Processing£©ÊÇÒ»ÖÖÖ§³Ö¹²ÏíÄÚ´æ²¢Ðбà³ÌµÄ±ê×¼¡£ËüÄܹ»ÔÚ¶à¸ö´¦Öóͷ£Æ÷½¹µãÖÐʵÏÖ²¢ÐÐÔËË㣬Ìá¸ß³ÌÐòµÄÖ´ÐÐЧÂÊ¡£±¾ÎĽ«ÏÈÈÝÔÚLinux²Ù×÷ϵͳÉÏʹÓÃOpenMP¾ÙÐв¢Ðбà³ÌµÄÉèÖÃÒªÁ죬²¢Í¨¹ý´úÂëʾÀý¾ÙÐÐÏêϸ˵Ã÷¡£
×°ÖÃOpenMPÖ§³Ö¿â
ÔÚLinuxÉÏʹÓÃOpenMP¾ÙÐв¢Ðбà³Ì֮ǰ£¬Ê×ÏÈÐèҪȷ±£OpenMPÖ§³Ö¿âÒѾװÖ᣷¿ªÖնˣ¬ÊäÈëÒÔÏÂÏÂÁîÀ´×°ÖÃOpenMPÖ§³Ö¿â£º
sudo apt-get install libomp-dev
µÇ¼ºó¸´ÖÆ
ÉèÖñàÒëÆ÷
ÔÚʹÓÃOpenMP¾ÙÐв¢Ðбà³Ì֮ǰ£¬ÐèÒªÔÚ±àÒëÆ÷ÖÐÆôÓÃOpenMPÖ§³Ö¡£´ó²¿·ÖLinux¿¯ÐаæĬÈÏʹÓÃGCC×÷Ϊ±àÒëÆ÷£¬ÎÒÃÇ¿ÉÒÔͨ¹ýÒÔÏ°취À´ÉèÖÃGCC±àÒëÆ÷µÄOpenMPÖ§³Ö£º
£¨1£©·¿ªÖնˣ¬ÊäÈëÒÔÏÂÏÂÁî·¿ªGCC±àÒëÆ÷µÄÉèÖÃÎļþ£º
sudo nano /etc/environment
µÇ¼ºó¸´ÖÆ
£¨2£©ÔÚ·¿ªµÄÉèÖÃÎļþÖÐÌí¼ÓÒÔÏÂÄÚÈÝ£º
OMP_NUM_THREADS=<n>
µÇ¼ºó¸´ÖÆ
ÆäÖУ¬ ´ú±í¿ÉÓÃÓÚ²¢ÐÐÅÌËãµÄÏß³ÌÊý¡£¿ÉÒÔƾ֤×Ô¼ºµÄÐèÒªÉèÖÃÒ»¸öºÏÊʵÄÊýÖµ¡£
£¨3£©ÉúÑIJ¢Í˳öÉèÖÃÎļþ¡£
ʹÓÃOpenMP¾ÙÐв¢Ðбà³Ì
ÉèÖÃÍê³Éºó£¬ÎÒÃÇ¿ÉÒÔʹÓÃOpenMP¾ÙÐв¢Ðбà³ÌÁË¡£ÏÂÃæÊÇÒ»¸ö¼òÆӵĴúÂëʾÀý£¬ÑÝʾÔõÑùʹÓÃOpenMP¶ÔÒ»¸öforÑ»·¾ÙÐв¢ÐÐÅÌË㣺
#include <stdio.h> #include <omp.h> int main() { // ÉèÖò¢ÐÐÇøÓò #pragma omp parallel { // »ñÈ¡Ï̱߳àºÅ int tid = omp_get_thread_num(); // »ñÈ¡Ïß³Ì×ÜÊý int num_threads = omp_get_num_threads(); printf("Hello from thread %d of %d ", tid, num_threads); } return 0; }
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊö´úÂëÖУ¬ÎÒÃÇʹÓÃomp_get_thread_num()º¯Êý»ñÈ¡Ä¿½ñÏ̵߳ıàºÅ£¬Ê¹ÓÃomp_get_num_threads()º¯Êý»ñÈ¡×ܵÄÏß³ÌÊý¡£Í¨¹ýÉÏÊö´úÂ룬ÎÒÃÇ¿ÉÒÔÊӲ쵽²î±ðÏ̵߳ÄÊä³öЧ¹û¡£
±àÒëºÍÔËÐÐOpenMP³ÌÐò
±àÒëOpenMP³ÌÐòÐèҪʹÓÃ-fopenmp²ÎÊý£¬ÒÔ¼û¸æ±àÒëÆ÷ÆôÓÃOpenMPÖ§³Ö¡£ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏÂÏÂÁîÀ´±àÒëÉÏÊöʾÀý´úÂ룺
gcc -fopenmp omp_example.c -o omp_example
µÇ¼ºó¸´ÖÆ
±àÒëÍê³Éºó£¬ÎÒÃÇ¿ÉÒÔÔËÐÐÌìÉúµÄ¿ÉÖ´ÐÐÎļþ£º
./omp_example
µÇ¼ºó¸´ÖÆ
ÔÚÔËÐÐЧ¹ûÖУ¬ÎÒÃÇ¿ÉÒÔ¿´µ½²î±ðÏ̵߳ÄÊä³öÐÅÏ¢¡£
²¢Ðбà³ÌµÄ×¢ÖØÊÂÏî
ʹÓÃOpenMP¾ÙÐв¢Ðбà³Ìʱ£¬ÐèҪעÖØÒÔϼ¸µã£º
£¨1£©²¢ÐÐÇøÓò£ºÊ¹ÓÃ#pragma omp parallelÖ¸ÁîÀ´½ç˵²¢ÐÐÇøÓò¡£
£¨2£©Ï̱߳àºÅ£ºÊ¹ÓÃomp_get_thread_num()º¯Êý»ñÈ¡Ä¿½ñÏ̵߳ıàºÅ¡£
£¨3£©Ïß³Ì×ÜÊý£ºÊ¹ÓÃomp_get_num_threads()º¯Êý»ñÈ¡×ܵÄÏß³ÌÊý¡£
£¨4£©Êý¾Ý¹²Ïí£º¿ÉÒÔʹÓÃprivateºÍsharedµÈÒªº¦×ÖÀ´ÉùÃ÷±äÁ¿µÄ¹²Ïí״̬¡£
£¨5£©Í¬²½»úÖÆ£º¿ÉÒÔʹÓÃ#pragma omp barrierÖ¸ÁîÀ´ÊµÏÖÏ̵߳Äͬ²½¡£
ͨ¹ýÒÔÉÏÉèÖúÍ×¢ÖØÊÂÏÎÒÃÇ¿ÉÒÔÔÚLinuxÉÏʹÓÃOpenMP¾ÙÐв¢Ðбà³Ì¡£Ê¹ÓÃOpenMPÄܹ»³ä·ÖʹÓöàºË´¦Öóͷ£Æ÷µÄÐÔÄÜ£¬¼ÓËÙ³ÌÐòµÄÔËÐС£Ï£Íû±¾ÎÄÄܹ»¶ÔÕýÔÚ¾ÙÐв¢Ðбà³ÌѧϰºÍÓ¦ÓõĶÁÕßÌṩһЩ×ÊÖú¡£
ÒÔÉϾÍÊÇÔÚLinuxÉÏʹÓÃOpenMP¾ÙÐв¢Ðбà³ÌµÄÉèÖÃÒªÁìµÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡