{"id":8893,"date":"2017-10-20T09:00:50","date_gmt":"2017-10-20T13:00:50","guid":{"rendered":"https:\/\/blogs.mathworks.com\/pick\/?p=8893"},"modified":"2017-11-03T18:33:19","modified_gmt":"2017-11-03T22:33:19","slug":"mex-multithreading","status":"publish","type":"post","link":"https:\/\/blogs.mathworks.com\/pick\/2017\/10\/20\/mex-multithreading\/","title":{"rendered":"Mex Multithreading"},"content":{"rendered":"<div xmlns:mwsh=\"https:\/\/www.mathworks.com\/namespace\/mcode\/v1\/syntaxhighlight.dtd\" class=\"content\">\n   <introduction><\/p>\n<p><a href=\"https:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/3208495\">Sean<\/a>&#8216;s pick this week is <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/21233-mex-multithreading\">Mex Multithreading<\/a> by <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/1097878\">Dirk-Jan Kroon<\/a>.\n      <\/p>\n<p>   <\/introduction><\/p>\n<p>My pick this week is an example of how to write multithreaded <a title=\"https:\/\/www.mathworks.com\/help\/matlab\/mex-file-applications.html (link no longer works)\">MEX functions<\/a> to take advantage of more of your computational cores.  MEX function allow you to include C\/C++ or Fortran code directly in MATLAB.\n   <\/p>\n<p>Since I don&#8217;t write very much C code myself (I usually cheat and use <a href=\"https:\/\/www.mathworks.com\/products\/matlab-coder.html\">MATLAB Coder<\/a>) it&#8217;s nice to see a simple example of how to accomplish a specific task in MEX. Dirk-Jan shows the header files to include (Windows only!) and the process for executing on multiple threads and using a <a href=\"https:\/\/stackoverflow.com\/questions\/34524\/what-is-a-mutex\">mutex<\/a> between them to update a percentage complete.\n   <\/p>\n<p>By using multiple threads, you can expedite the C code and not have to make memory copies like you would have to by using <a href=\"https:\/\/www.mathworks.com\/products\/parallel-computing.html\">Parallel Computing<\/a>.  I do a lot of Parallel Computing but some times am asked how to do both multithreading AND parallel computing together.  You might want to do both if you have fewer jobs to run than cores available or if memory requirements are high.  This is a good example of one way to go about that.  You could compile the MEX function and then call it inside of your favorite parallel construct.  Of course, many MATLAB functions are already multithreaded so often it will happen implicitly.\n   <\/p>\n<p>Here&#8217;s a look at my Task Manager while running <tt>square<\/tt> so you can see the different threads in action.  <tt>square<\/tt> is also updating the percentage to the command line as it goes.\n   <\/p>\n<pre style=\"background: #F9F7F3; padding: 10px; border: 1px solid rgb(200,200,200)\">y = square(magic(500));<\/pre>\n<pre style=\"font-style:oblique\">finished: 0 \r\nfinished: 0 \r\nfinished: 0\r\n:\r\n\/\/snip for brevity\/\/\r\n:\r\nfinished: 99 \r\nfinished: 99 \r\n<\/pre>\n<p><img decoding=\"async\" vspace=\"5\" hspace=\"5\" src=\"https:\/\/blogs.mathworks.com\/images\/pick\/Sean\/mainMexMulti\/taskmanager.png\"> <\/p>\n<p>Do you write C\/C++ and need to pull it into MATLAB?  Have you used multithreading from within MEX and have any pro-tips to offer?\n   <\/p>\n<p>Give it a try and let us know what you think <a href=\"https:\/\/blogs.mathworks.com\/pick\/?p=8893#respond\">here<\/a> or leave a <a href=\"https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/21233-mex-multithreading#comments\">comment<\/a> for Dirk-Jan.\n   <\/p>\n<p><script language=\"JavaScript\">\n<!--\n\n    function grabCode_8e363ef7a2b0424aadb121e0c9518e37() {\n        \/\/ Remember the title so we can use it in the new page\n        title = document.title;\n\n        \/\/ Break up these strings so that their presence\n        \/\/ in the Javascript doesn't mess up the search for\n        \/\/ the MATLAB code.\n        t1='8e363ef7a2b0424aadb121e0c9518e37 ' + '##### ' + 'SOURCE BEGIN' + ' #####';\n        t2='##### ' + 'SOURCE END' + ' #####' + ' 8e363ef7a2b0424aadb121e0c9518e37';\n    \n        b=document.getElementsByTagName('body')[0];\n        i1=b.innerHTML.indexOf(t1)+t1.length;\n        i2=b.innerHTML.indexOf(t2);\n \n        code_string = b.innerHTML.substring(i1, i2);\n        code_string = code_string.replace(\/REPLACE_WITH_DASH_DASH\/g,'--');\n\n        \/\/ Use \/x3C\/g instead of the less-than character to avoid errors \n        \/\/ in the XML parser.\n        \/\/ Use '\\x26#60;' instead of '<' so that the XML parser\n        \/\/ doesn't go ahead and substitute the less-than character. \n        code_string = code_string.replace(\/\\x3C\/g, '\\x26#60;');\n\n        author = 'Sean de Wolski';\n        copyright = 'Copyright 2017 The MathWorks, Inc.';\n\n        w = window.open();\n        d = w.document;\n        d.write('\n\n<pre>\\n');\r\n        d.write(code_string);\r\n\r\n        \/\/ Add author and copyright lines at the bottom if specified.\r\n        if ((author.length > 0) || (copyright.length > 0)) {\r\n            d.writeln('');\r\n            d.writeln('%%');\r\n            if (author.length > 0) {\r\n                d.writeln('% _' + author + '_');\r\n            }\r\n            if (copyright.length > 0) {\r\n                d.writeln('% _' + copyright + '_');\r\n            }\r\n        }\r\n\r\n        d.write('<\/pre>\n\n\\n');\n      \n      d.title = title + ' (MATLAB code)';\n      d.close();\n      }   \n      \n-->\n<\/script><\/p>\n<p style=\"text-align: right; font-size: xx-small; font-weight:lighter;   font-style: italic; color: gray\"><a href=\"javascript:grabCode_8e363ef7a2b0424aadb121e0c9518e37()\"><span style=\"font-size: x-small;        font-style: italic;\">Get<br \/>\n            the MATLAB code<br \/>\n            <noscript>(requires JavaScript)<\/noscript><\/span><\/a><\/p>\n<p>      Published with MATLAB&reg; R2017b<\/p>\n<\/div>\n<p><!--\n8e363ef7a2b0424aadb121e0c9518e37 ##### SOURCE BEGIN #####\n%% Mex Multithreading\n%\n% <https:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/3208495 Sean>'s pick this week is\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/21233-mex-multithreading Mex Multithreading> by\n% <https:\/\/www.mathworks.com\/matlabcentral\/profile\/authors\/1097878 Dirk-Jan Kroon>.\n% \n\n%% \n% My pick this week is an example of how to write multithreaded\n% <https:\/\/www.mathworks.com\/help\/matlab\/mex-file-applications.html MEX\n% functions> to take advantage of more of your computational cores.  MEX\n% function allow you to include C\/C++ or Fortran code directly in MATLAB.\n%\n% Since I don't write very much C code myself (I usually cheat and use\n% <https:\/\/www.mathworks.com\/products\/matlab-coder.html MATLAB Coder>) it's\n% nice to see a simple example of how to accomplish a specific task in MEX.\n% Dirk-Jan shows the header files to include (Windows only!) and the\n% process for executing on multiple threads and using a\n% <https:\/\/stackoverflow.com\/questions\/34524\/what-is-a-mutex mutex> between\n% them to update a percentage complete.\n%\n% By using multiple threads, you can expedite the C code and not have to\n% make memory copies like you would have to by using\n% <https:\/\/www.mathworks.com\/products\/parallel-computing.html Parallel\n% Computing>.  I do a lot of Parallel Computing but some times am asked how\n% to do both multithreading AND parallel computing together.  You might\n% want to do both if you have fewer jobs to run than cores available or if\n% memory requirements are high.  This is a good example of one way to go\n% about that.  You could compile the MEX function and then call it inside\n% of your favorite parallel construct.  Of course, many MATLAB functions\n% are already multithreaded so often it will happen implicitly.\n%\n% Here's a look at my Task Manager while running |square| so you can see\n% the different threads in action.  |square| is also updating the\n% percentage to the command line as it goes.\n\ny = square(magic(500));\n\n%%\n%\n% <<taskmanager.png>>\n\n%%\n% Do you write C\/C++ and need to pull it into MATLAB?  Have you used\n% multithreading from within MEX and have any pro-tips to offer?\n% \n% Give it a try and let us know what you think\n% <https:\/\/blogs.mathworks.com\/pick\/?p=8893#respond here> or leave a\n% <https:\/\/www.mathworks.com\/matlabcentral\/fileexchange\/21233-mex-multithreading#comments\n% comment> for Dirk-Jan.\n%\n \n\n##### SOURCE END ##### 8e363ef7a2b0424aadb121e0c9518e37\n--><\/p>\n","protected":false},"excerpt":{"rendered":"<div class=\"overview-image\"><img decoding=\"async\"  class=\"img-responsive\" src=\"https:\/\/blogs.mathworks.com\/images\/pick\/Sean\/mainMexMulti\/taskmanager.png\" onError=\"this.style.display ='none';\" \/><\/div>\n<p>Sean&#8216;s pick this week is Mex Multithreading by Dirk-Jan Kroon.<\/p>\n<p>My pick this week is an example of how to write multithreaded MEX functions to take advantage of more of your&#8230; <a class=\"read-more\" href=\"https:\/\/blogs.mathworks.com\/pick\/2017\/10\/20\/mex-multithreading\/\">read more >><\/a><\/p>\n","protected":false},"author":87,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[7,16,6],"tags":[],"_links":{"self":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/8893"}],"collection":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/users\/87"}],"replies":[{"embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/comments?post=8893"}],"version-history":[{"count":4,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/8893\/revisions"}],"predecessor-version":[{"id":8927,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/posts\/8893\/revisions\/8927"}],"wp:attachment":[{"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/media?parent=8893"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/categories?post=8893"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/blogs.mathworks.com\/pick\/wp-json\/wp\/v2\/tags?post=8893"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}